# 写入文件 > 原文: [https://pythonbasics.org/write-file/](https://pythonbasics.org/write-file/) 写入文件功能是标准模块的一部分,您无需包含任何模块。 _ 写入文件 _ 的文件和 _ 在 Python 语言中是不同的。 您可以使用 行打开要写入的文件 _ ```py f = open("test.txt","w") ``` to append to a file use: ```py f = open("test.txt","a") ``` 如果指定了错误的参数,则文件可能被清空! ## 示例 ### 创建新文件 要创建新文件,可以使用以下代码: ```py #!/usr/bin/env python # create and open file f = open("test.txt","w") # write data to file f.write("Hello World, \n") f.write("This data will be written to the file.") # close file f.close() ``` The ‘\n’ character adds a new line. If the file already exists, it is replaced. If you use the “w” parameter, the existing contents of the file will be deleted. ### 附加到文件 要将文本添加到文件末尾,请使用“ a”参数。 ```py #!/usr/bin/env python # create and open file f = open("test.txt","a") # write data to file f.write("Don't delete existing data \n") f.write("Add this to the existing file.") # close file f.close() ``` ## 练习 1. 将文本“轻松”写到文件中 2. 将 open(“ text.txt”)行写入文件 [下载示例](https://gum.co/dcsp)