首頁 >後端開發 >Python教學 >如何在Python中讀取和寫文件?

如何在Python中讀取和寫文件?

Robert Michael Kim
Robert Michael Kim原創
2025-03-10 18:46:49330瀏覽

如何在Python中讀取和編寫文件?

Python提供了一種使用其內置功能與文件進行交互的直接方法。核心功能圍繞 open()函數,該功能以文件路徑和模式為參數。 Let's explore reading and writing:

Reading Files:

To read a file, you typically use the open() function with the 'r' mode (read mode) and then use methods like read(), readline(), or readlines() to access the file's content.

<code class="python"># Open a file for reading try: with open("my_file.txt", "r") as file: # Read the entire file content at once contents = file.read() print(contents) # Read the file line by line file.seek(0) # Reset the file pointer to the beginning for line in file: print(line, end="") # end=""預防額外的新線#讀取所有行中的所有行在文件中行</code>按行讀取行,<code> readlines()</code>將所有行讀取到列表中。 <code>用打開(...)作為文件:</code>構造確保即使發生錯誤也會自動關閉文件。 <p> <strong>編寫文件:</strong> </p> <p>寫入文件中涉及以'w'(寫入)模式打開其,'a'(append)模式,或'x'(x'x'(獨家創建)模式。 <code> write()</code>方法將內容添加到文件中。</p> <pre class="brush:php;toolbar:false">  try:with open(&my_new_file.txt.txt)作為文件:file.write(quot); ile.txt“ a”)作為文件:#Append模式file.write(“此行”附加。 Remember to include newline characters (<code>\n</code>) for proper line breaks.<h2>What are the different file modes available in Python for file I/O?</h2><p>Python's <code>open()</code> function supports several file access modes, each dictating how the file is handled:</p>
  • 'r' (read): Opens the file for reading.這是默認模式。如果文件不存在,則會發生錯誤。
  • 'w'(寫):打開寫作文件。如果不存在,則創建一個新文件,並在內容上覆蓋。
  • 'x'(獨家創建):僅在不存在的情況下才能打開寫作文件。如果文件存在,則會引起錯誤。
  • 'a'(附錄):打開寫作文件。如果文件存在,則將新數據附加到最後;否則,創建了一個新文件。
  • 'b'(二進制):與其他模式('rb','wb','ab','xb'一起使用)。以二進制模式打開文件,適用於非文本文件(圖像,可執行文件等)。
  • 't'(text):與其他模式('rt','wt','wt','at'at'xt','xt'一起使用。這是默認模式,用於文本文件。它根據系統的約定處理新線字符。
  • ''(update):與其他模式('r','w','a','','x'一起使用)。允許閱讀和寫入文件。 “ r”允許從一開始就讀取和寫作,'w'覆蓋,“ a”附加。

可以將這些模式組合在一起。例如,'r b&quot'在二進制模式下讀取和寫作的文件。

在python中讀取或編寫文件時,我如何處理潛在的錯誤?

文件I/O操作i/o操作,例如遇到各種錯誤,例如不充分的文件,不充分的允許允許允許允許。強大的代碼應優雅處理。最常見的方法是使用 try-except 阻止:

 嘗試:開放('my_file.txt; r&quort'r&quort; ;特定異常(<code> filenotfoundError </code>,<code> permissionError </code>,<code> oserror </code>),以獲取更有信息的錯誤處理和通用<code> exception </code>以捕獲任何其他潛在問題。始終在可能的情況下有效處理錯誤。 <h2>在Python中有效讀取和編寫大文件的最佳實踐是什麼?</h2> <p>讀取和編寫大型文件需要優化以避免記憶問題並提高性能。以下是一些最佳實踐:</p> 
  • 按行劃線:避免一次將整個文件加載到內存中。如第一個示例所示,使用循環的循環的逐行迭代。 This is significantly more memory-efficient for large files.
  • Use buffered I/O: The io.BufferedReader and io.BufferedWriter classes provide buffered I/O, which significantly improves performance by reducing the number of disk accesses.
  • Generators: For very large files, using generators can further improve memory efficiency.生成器會按需產生值,避免將整個文件加載到內存中。
  • 塊:讀取並寫入特定大小的塊而不是一次處理文件。這可以最大程度地減少內存使用情況並允許進度更新。
  • 內存映射:用於隨機訪問大型文件,請考慮使用 mmap (內存映射)。這將文件的一部分映射到內存,允許對特定部分有效訪問,而無需加載整個文件。
 <pre class="brush:php;toolbar:false"> <code class="“" python>導入io import io import mmap #chunking示例chunk_size = 1024帶有open(零件#... #memory映射示例帶有open('groot_file.txt'r b&quot“ r b&quot”)作為f:mm = mmap.mmap(f.fileno(0),0)#0表示映射整個文件#access #access使用mm [start:啟動:啟動:對於順序處理,逐行迭代或使用緩衝I/O通常就足夠了。對於隨機訪問,內存映射可能更合適。對於超出可用RAM的極大文件,請考慮使用專門的庫,例如<code> dask </code>或<code> vaex </code>處理核心外計算。</code>

以上是如何在Python中讀取和寫文件?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn