大家好句狼,我是 V 哥笋熬。今天的內(nèi)容來介紹 Python 中進行文件讀寫操作的方法,這在學習 Python 時是必不可少的技術(shù)點腻菇,希望可以幫助到正在學習 python的小伙伴胳螟。
以下是 Python 中進行文件讀寫操作的基本方法:
一昔馋、文件讀取:
# 打開文件
with open('example.txt', 'r') as file:
# 讀取文件的全部內(nèi)容
content = file.read()
print(content)
# 將文件指針重置到文件開頭
file.seek(0)
# 逐行讀取文件內(nèi)容
lines = file.readlines()
for line in lines:
print(line.strip()) # 去除行末的換行符
# 將文件指針重置到文件開頭
file.seek(0)
# 逐行讀取文件內(nèi)容的另一種方式
for line in file:
print(line.strip())
代碼解釋:
-
open('example.txt', 'r')
:以只讀模式r
打開名為example.txt
的文件。 -
with
語句:確保文件在使用完畢后自動關閉糖耸,避免資源泄漏秘遏。 -
file.read()
:讀取文件的全部內(nèi)容。 -
file.seek(0)
:將文件指針重置到文件開頭蔬捷,以便重新讀取垄提。 -
file.readlines()
:將文件內(nèi)容按行讀取,并存儲在一個列表中周拐,每一行是列表的一個元素铡俐。 -
for line in file
:逐行讀取文件內(nèi)容,file
對象是可迭代的妥粟,每次迭代返回一行审丘。
二、文件寫入:
# 打開文件進行寫入
with open('output.txt', 'w') as file:
# 寫入內(nèi)容
file.write("Hello, World!\n")
file.write("This is a new line.")
代碼解釋:
-
open('output.txt', 'w')
:以寫入模式w
打開文件勾给,如果文件不存在滩报,會創(chuàng)建文件;如果文件存在播急,會清空原文件內(nèi)容脓钾。 -
file.write()
:將指定內(nèi)容寫入文件,不會自動添加換行符桩警,若需要換行可训,需手動添加\n
。
三捶枢、文件追加:
# 打開文件進行追加
with open('output.txt', 'a') as file:
# 追加內(nèi)容
file.write("\nThis is an appended line.")
代碼解釋:
-
open('output.txt', 'a')
:以追加模式a
打開文件握截,在文件末尾添加新內(nèi)容,不會覆蓋原文件內(nèi)容烂叔。
四谨胞、文件讀寫的二進制模式:
# 以二進制模式讀取文件
with open('example.bin', 'rb') as file:
binary_data = file.read()
print(binary_data)
# 以二進制模式寫入文件
with open('output.bin', 'wb') as file:
binary_data = b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64' # 二進制數(shù)據(jù)
file.write(binary_data)
代碼解釋:
-
open('example.bin', 'rb')
:以二進制只讀模式rb
打開文件。 -
open('output.bin', 'wb')
:以二進制寫入模式wb
打開文件蒜鸡。 -
b'\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64'
:表示二進制數(shù)據(jù)胯努,使用b
前綴。
五逢防、使用 json
模塊讀寫 JSON 文件:
import json
# 寫入 JSON 數(shù)據(jù)
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.json', 'w') as file:
json.dump(data, file)
# 讀取 JSON 數(shù)據(jù)
with open('data.json', 'r') as file:
loaded_data = json.load(file)
print(loaded_data)
代碼解釋:
-
json.dump(data, file)
:將 Python 對象data
序列化為 JSON 格式并寫入文件康聂。 -
json.load(file)
:從文件中讀取 JSON 數(shù)據(jù)并解析為 Python 對象。
六胞四、使用 csv
模塊讀寫 CSV 文件:
import csv
# 寫入 CSV 數(shù)據(jù)
data = [['Name', 'Age', 'City'], ['John', 30, 'New York'], ['Jane', 25, 'Chicago']]
with open('data.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(data)
# 讀取 CSV 數(shù)據(jù)
with open('data.csv', 'r') as file:
reader = csv.reader(file)
for row in reader:
print(row)
代碼解釋:
-
csv.writer(file)
:創(chuàng)建一個 CSV 寫入對象,將數(shù)據(jù)列表寫入文件伶椿。 -
writer.writerows(data)
:將數(shù)據(jù)列表中的每一行寫入文件辜伟。 -
csv.reader(file)
:創(chuàng)建一個 CSV 讀取對象氓侧,逐行讀取文件。
七导狡、使用 pandas
模塊讀寫文件(需要安裝 pandas
庫):
import pandas as pd
# 寫入數(shù)據(jù)到 CSV 文件
data = {'Name': ['John', 'Jane'], 'Age': [30, 25], 'City': ['New York', 'Chicago']}
df = pd.DataFrame(data)
df.to_csv('data_pandas.csv', index=False)
# 讀取 CSV 文件
df_read = pd.read_csv('data_pandas.csv')
print(df_read)
代碼解釋:
-
pd.DataFrame(data)
:將字典數(shù)據(jù)轉(zhuǎn)換為pandas
的DataFrame
對象约巷。 -
df.to_csv('data_pandas.csv', index=False)
:將DataFrame
對象存儲為 CSV 文件,不保存索引旱捧。 -
pd.read_csv('data_pandas.csv')
:讀取 CSV 文件為DataFrame
對象独郎。
八、使用 pickle
模塊進行對象序列化和反序列化:
import pickle
# 序列化對象
data = {'name': 'John', 'age': 30, 'city': 'New York'}
with open('data.pkl', 'wb') as file:
pickle.dump(data, file)
# 反序列化對象
with open('data.pkl', 'rb') as file:
loaded_data = pickle.load(file)
print(loaded_data)
代碼解釋:
-
pickle.dump(data, file)
:將 Python 對象data
序列化為二進制數(shù)據(jù)并寫入文件枚赡。 -
pickle.load(file)
:從文件中讀取二進制數(shù)據(jù)并反序列化為 Python 對象氓癌。
以上是 Python 中進行文件讀寫操作的常用方法,你可以根據(jù)不同的文件類型和使用場景贫橙,選擇合適的方法進行操作贪婉。
最后
根據(jù)文件類型和操作需求,可以靈活使用內(nèi)置的 open 函數(shù)及相關模塊卢肃,如 json疲迂、csv、pandas 和 pickle 等莫湘,同時利用 with 語句確保文件的正確打開和關閉尤蒿。你 Get 到了么,歡迎關注威哥愛編程幅垮,全棧路上我們并肩前行腰池。