使用Python進行文件讀寫操作的基本方法
更新時間:2025年01月21日 08:41:22 作者:威哥愛編程
今天的內(nèi)容來介紹 Python 中進行文件讀寫操作的方法,這在學習 Python 時是必不可少的技術(shù)點,希望可以幫助到正在學習 python的小伙伴,以下是 Python 中進行文件讀寫操作的基本方法,需要的朋友可以參考下
一、文件讀?。?/h2>
# 打開文件
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())
# 打開文件 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 到了么,歡迎關注威哥愛編程,全棧路上我們并肩前行。
以上就是使用Python進行文件讀寫操作的基本方法的詳細內(nèi)容,更多關于Python文件讀寫操作的資料請關注腳本之家其它相關文章!
相關文章
Django項目創(chuàng)建到啟動詳解(最全最詳細)
這篇文章主要給大家介紹了關于Django項目創(chuàng)建到啟動的步驟,本文介紹的方法算是最全最詳細的一個項目,需要的朋友可以參考下2019-09-09使用python批量讀取word文檔并整理關鍵信息到excel表格的實例
今天小編就為大家分享一篇使用python批量讀取word文檔并整理關鍵信息到excel表格的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11