如何在Python 中使用多個Open 語句改進文件處理
在Python 中,open() 函數是用於文件輸入的多功能工具和輸出。當處理多個檔案時,使用 with 語句來確保正確的資源管理是有利的。
情況:
考慮一個從檔案讀取名稱的程式碼片段,將附加文字附加到特定名稱。當前的實現按順序打開文件,這可能不是最佳的。
解決方案:
Python 允許在單一 with 語句中透過逗號分隔使用多個 open() 語句他們。這可以同時處理多個文件並增強資源管理。
def filter(txt, oldfile, newfile):
'''
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] ' - Truly a great person!\n'
outfile.write(line)
附加說明:
透過以這種方式優化文件處理,開發人員可以增強程式碼可讀性、資源管理和整體效率。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3