」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何在 Python 中使用多個「open()」語句簡化檔案處理?

如何在 Python 中使用多個「open()」語句簡化檔案處理?

發佈於2024-11-22
瀏覽:182

How to Streamline File Handling with Multiple `open()` Statements in Python?

如何在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)

附加說明:

  • 從沒有回傳值的函數中明確傳回是不必要的。
  • 此功能在 Python 2.7 和 3.1 或更高版本中引入。
  • 如果與 Python 版本 2.5 或 2.6 相容必需,建議使用語句嵌套或使用 contextlib.nested。

透過以這種方式優化文件處理,開發人員可以增強程式碼可讀性、資源管理和整體效率。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3