Python文本與二進制文件讀寫操作指南
引言
文件讀寫是編程中的常見操作,Python提供了簡潔且強大的文件操作接口。本文將詳細介紹Python中文本文件和二進制文件的讀寫操作,包括文件打開、讀取、寫入、關(guān)閉及異常處理等內(nèi)容,并通過具體示例代碼展示如何高效地處理文件。
文件的基本操作
打開文件
在Python中,使用open函數(shù)打開文件。open函數(shù)的基本語法如下:
open(filename, mode, encoding=None)
filename:要打開的文件名。mode:文件打開模式,如'r'(讀?。?code>'w'(寫入)、'a'(追加)等。encoding:文本文件的編碼方式,通常使用'utf-8'。
文件模式
常見的文件打開模式包括:
'r':只讀模式(默認)。'w':寫入模式,會覆蓋文件內(nèi)容。'a':追加模式,在文件末尾添加內(nèi)容。'b':二進制模式。'+':讀寫模式。
文本文件處理
讀取文本文件
逐行讀取
使用readline方法逐行讀取文件內(nèi)容:
with open('example.txt', 'r', encoding='utf-8') as file:
line = file.readline()
while line:
print(line.strip())
line = file.readline()
讀取整個文件
使用read方法一次性讀取整個文件內(nèi)容:
with open('example.txt', 'r', encoding='utf-8') as file:
content = file.read()
print(content)
讀取文件的所有行
使用readlines方法讀取文件的所有行,并返回一個列表:
with open('example.txt', 'r', encoding='utf-8') as file:
lines = file.readlines()
for line in lines:
print(line.strip())
寫入文本文件
使用write方法寫入文本文件:
with open('output.txt', 'w', encoding='utf-8') as file:
file.write('這是第一行文本。\n')
file.write('這是第二行文本。')
追加文本文件
使用append模式在文件末尾追加內(nèi)容:
with open('output.txt', 'a', encoding='utf-8') as file:
file.write('\n這是追加的一行文本。')
二進制文件處理
讀取二進制文件
使用rb模式讀取二進制文件:
with open('example.bin', 'rb') as file:
content = file.read()
print(content)
寫入二進制文件
使用wb模式寫入二進制文件:
with open('output.bin', 'wb') as file:
file.write(b'This is a binary file.')
異常處理
在文件操作過程中,可能會遇到一些異常情況,如文件不存在、沒有權(quán)限等??梢允褂?code>try-except語句進行異常處理:
try:
with open('nonexistent.txt', 'r', encoding='utf-8') as file:
content = file.read()
except FileNotFoundError:
print('文件未找到。')
except PermissionError:
print('沒有權(quán)限讀取文件。')
實際應用示例
復制文本文件
def copy_text_file(source, destination):
try:
with open(source, 'r', encoding='utf-8') as src_file:
content = src_file.read()
with open(destination, 'w', encoding='utf-8') as dest_file:
dest_file.write(content)
print(f'文件已成功復制到 {destination}')
except Exception as e:
print(f'復制文件時出錯: {e}')
copy_text_file('example.txt', 'example_copy.txt')
復制二進制文件
def copy_binary_file(source, destination):
try:
with open(source, 'rb') as src_file:
content = src_file.read()
with open(destination, 'wb') as dest_file:
dest_file.write(content)
print(f'文件已成功復制到 {destination}')
except Exception as e:
print(f'復制文件時出錯: {e}')
copy_binary_file('example.bin', 'example_copy.bin')
統(tǒng)計文本文件的行數(shù)、單詞數(shù)和字符數(shù)
def file_statistics(filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
lines = file.readlines()
line_count = len(lines)
word_count = sum(len(line.split()) for line in lines)
char_count = sum(len(line) for line in lines)
print(f'行數(shù): {line_count}, 單詞數(shù): {word_count}, 字符數(shù): {char_count}')
except Exception as e:
print(f'統(tǒng)計文件時出錯: {e}')
file_statistics('example.txt')
使用JSON文件
JSON是一種常用的輕量級數(shù)據(jù)交換格式。在Python中,可以使用json模塊讀寫JSON文件。
讀取JSON文件
import json
def read_json(filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
data = json.load(file)
return data
except Exception as e:
print(f'讀取JSON文件時出錯: {e}')
return None
data = read_json('data.json')
print(data)
寫入JSON文件
import json
def write_json(data, filename):
try:
with open(filename, 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4)
print(f'數(shù)據(jù)已寫入到 {filename}')
except Exception as e:
print(f'寫入JSON文件時出錯: {e}')
data = {'name': 'Alice', 'age': 25, 'city': 'New York'}
write_json(data, 'data.json')
總結(jié)
本文詳細介紹了Python中文本文件和二進制文件的讀寫操作,包括文件的打開、讀取、寫入、追加和關(guān)閉等基本操作,同時講解了如何進行異常處理。通過具體的示例代碼,展示了如何高效地處理文件,例如逐行讀取文件、寫入文件、復制文件、統(tǒng)計文件信息以及處理JSON文件等實際應用場景。掌握這些文件操作技巧,能夠幫助大家在Python編程中更加靈活地處理各種文件,提高代碼的可讀性和可維護性。
以上就是Python文本與二進制文件讀寫操作指南的詳細內(nèi)容,更多關(guān)于Python文本與二進制文件讀寫的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
實現(xiàn)python版本的按任意鍵繼續(xù)/退出
本文給大家簡單介紹了在windows以及l(fā)inux下實現(xiàn)python版本的按任意鍵繼續(xù)/退出功能,非常的簡單實用,linux下稍微復雜些,有需要的小伙伴可以參考下2016-09-09
通過Python的speech_recognition庫將音頻文件轉(zhuǎn)為文字
recognize_google()?是Google提供的一種語音識別API,可以識別音頻文件或麥克風錄制的語音,并將其轉(zhuǎn)換為文本,這篇文章主要介紹了通過Python的speech_recognition庫將音頻文件轉(zhuǎn)為文字,需要的朋友可以參考下2023-05-05
Python+PuLP實現(xiàn)線性規(guī)劃的求解
線性規(guī)劃(Linear?programming),在線性等式或不等式約束條件下求解線性目標函數(shù)的極值問題,常用于解決資源分配、生產(chǎn)調(diào)度和混合問題。本文將利用PuLP實現(xiàn)線性規(guī)劃的求解,需要的可以參考一下2022-04-04
人工智能學習Pytorch數(shù)據(jù)集分割及動量示例詳解
這篇文章主要為大家介紹了人工智能學習Pytorch數(shù)據(jù)集分割及動量示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步2021-11-11
Python爬蟲模擬登陸嗶哩嗶哩(bilibili)并突破點選驗證碼功能
這篇文章主要介紹了Python爬蟲模擬登陸嗶哩嗶哩(bilibili)并突破點選驗證碼功能,本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12
Pandas.DataFrame重置列的行名實現(xiàn)(set_index)
本文主要介紹了Pandas.DataFrame重置列的行名實現(xiàn)(set_index),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02

