写入现有文件
要写入现有文件,必须向open()函数添加参数 :
- "a" - 追加 - 将追加到文件末尾
- "w" - 写 - 将覆盖任何现有内容
打开文件“demofile2.txt”,并将内容附加到该文件:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
打开文件“ demofile3.txt”并覆盖内容:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
注意: “w”方法将覆盖整个文件。