首頁  >  文章  >  後端開發  >  python怎麼讀取文本文檔

python怎麼讀取文本文檔

下次还敢
下次还敢原創
2024-04-20 17:50:181044瀏覽

有四種方法可以使用Python 讀取文本文檔:直接讀取整個文件內容按行讀取文件內容並儲存在列表中逐行迭代文件內容指定文件的編碼、讀取模式和換行符等可選參數

python怎麼讀取文本文檔

如何使用Python 讀取文字文件

##直接方法:

<code class="python">with open("filename.txt", "r") as f:
    contents = f.read()</code>

按行讀取:

<code class="python">with open("filename.txt", "r") as f:
    lines = f.readlines()</code>

#逐行迭代:

<code class="python">with open("filename.txt", "r") as f:
    for line in f:
        # 对每一行进行操作</code>

其他可選參數:

  • encoding:指定檔案的編碼,例如"utf-8"。
  • mode:讀取模式,"r" 為唯讀,"w" 為唯寫,"a" 為追加。
  • newline:用於控制換行符,預設值為作業系統預設換行符。

範例:

讀取名為"example.txt" 的檔案並列印其內容:

<code class="python">with open("example.txt", "r") as f:
    contents = f.read()
print(contents)</code>
讀取"example .txt" 檔案的每一行並將其儲存在清單中:

<code class="python">with open("example.txt", "r") as f:
    lines = f.readlines()
print(lines)</code>
逐行讀取"example.txt" 檔案並列印每一行:

<code class="python">with open("example.txt", "r") as f:
    for line in f:
        print(line)</code>

以上是python怎麼讀取文本文檔的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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