Python 如何向文件中追加文字
Jinku Hu
2020年6月25日
2018年7月19日
你可以通过指定文件打开模式 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
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