写入文件功能是标准模块的一部分,您无需包含任何模块。
写入和附加到文件在 Python 语言中是不同的。您可以使用这行打开要写入的文件:
f = open("test.txt","w")
附加到文件中使用:
f = open("test.txt","a")
如果指定了错误的参数,则文件可能被清空!
示例
创建新文件
要创建新文件,可以使用以下代码:
#!/usr/bin/env python# create and open filef = open("test.txt","w")# write data to filef.write("Hello World, \n")f.write("This data will be written to the file.")# close filef.close()
"\n"字符添加新行。 如果文件已经存在,则将其替换。 如果使用"w"参数,则文件的现有内容将被删除。
附加到文件
要将文本添加到文件末尾,请使用"a"参数。
#!/usr/bin/env python# create and open filef = open("test.txt","a")# write data to filef.write("Don't delete existing data \n")f.write("Add this to the existing file.")# close filef.close()
练习
- 将文本“轻松”写到文件中
- 将
open("text.txt")行写入文件
