Python File Write
- 上一页 Python File Read
- 下一页 Python File Delete
Schrijven naar bestaand bestand
Om een bestaand bestand te schrijven, moet je open()
Voeg parameters toe aan de functie:
"a"
- Toevoegen - zal aan het einde van het bestand worden toegevoegd"w"
- Schrijven - zal elk bestaand inhoud overschrijven
实例
Open het bestand "demofile2.txt" en voeg de inhoud toe aan het bestand:
f = open("demofile2.txt", "a") f.write("Nu nu het bestand heeft meer inhoud!") f.close() # 追加后,打开并读取该文件: 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() # 写入后,打开并读取该文件: 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")
- 上一页 Python File Read
- 下一页 Python File Delete