Python 写入文件
写入现有文件
要写入现有文件,必须向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” 参数将覆盖整个文件。
创建一个新文件
要在Python中创建新文件,请使用在open()方法中使用以下参数之一:
"x" - 创建 - 将创建一个文件,如果文件存在则返回错误
"a" - 附加 - 如果指定的文件不存在,将创建一个文件
"w" - 写入 - 如果指定的文件不存在,将创建一个文件
实例
创建一个名为“myfile.txt”的文件:f = open("myfile.txt", "x")
实例
如果新文件不存在,请创建一个新文件:f = open("myfile.txt", "w")
