发布于 7个月前

Python 文件操作:写入文件

仍然使用open()函数,将模式改为w或a打开文件来创建文件对象。w模式下会覆盖旧数据写入新数据,a模式下可在原有数据基础上增加新数据。

>>> # 向文件中写入新数据
... with open("hello3.txt", 'w') as file:
...     text_to_write = "Hello Files From Writing"
...     file.write(text_to_write)
... 
>>> # 增加一些数据
... with open("hello3.txt", 'a') as file:
...     text_to_write = "\nHello Files From Appending"
...     file.write(text_to_write)
... 
>>> # 检查文件数据是否正确
... with open("hello3.txt") as file:
...     print(file.read())
... 
Hello Files From Writing
Hello Files From Appending

上面每次打开文件时都使用with语句。

with语句为我们创建了一个处理文件的上下文,当我们完成文件操作后,它可以关闭文件对象。这点很重要,如果我们不及时关闭打开的文件对象,它很有可能会被损坏。

©2020 edoou.com   京ICP备16001874号-3