问Python如何写入文件?

答 1 个回答|292 次阅读
Coco老师 - 官方公众号:青少儿编程学习网
擅长:编程教育网站:https://kidscodes.cn/

仍然使用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 = "
Hello 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语句为我们创建了一个处理文件的上下文,当我们完成文件操作后,它可以关闭文件对象。这点很重要,如果我们不及时关闭打开的文件对象,它很有可能会被损坏。

推荐课程 »更多

    推荐问答

    推荐知识

    Python精选库大全,青少年Python编程学习总结

    Python最适合青少儿进阶学习的编程语言