Python 如何向檔案中追加文字

Jinku Hu 2020年6月25日 2018年7月19日
Python 如何向檔案中追加文字

你可以通過指定檔案開啟模式 a 或者 a+ 來開啟檔案並且隨後向其增加文字。

destFile = r"C:\Test\Test.txt"
with open(destFile, 'a') as f:
    f.write("some appended text")

這個例子中,在檔案 C:\Test\Test.txt 的最後一個字元後面追加了字串 some appended text,如果原檔案是以 this is the last sentence 結尾的,那麼追加文字後,它就變成了 this is the last sentencesome appended text

追加文字中的新一行

如果你更喜歡在新的一行中新增文字,那麼你就需要在原檔案的後面首先加上換行符 \r\n 來確保新增加的文字是在新的一行中。

destFile = r"C:\Test\Test.txt"
with open(destFile, 'a') as f:
    f.write("the first appended text\r\n")
    f.write("the second appended text\r\n")
    f.write("the third appended text\r\n")
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn

相關文章 - Python File