上一篇
python如何清空文件
- 行业动态
- 2024-04-14
- 2
在Python中,可以使用以下方法清空文件:
1、打开文件并立即关闭,这将删除文件中的所有内容。
with open("file.txt", "w") as file: pass
2、使用os
模块的truncate()
函数清空文件。
import os with open("file.txt", "r+") as file: os.truncate(file.fileno(), 0)
3、使用open()
函数以写入模式打开文件,然后立即关闭。
with open("file.txt", "w") as file: pass
4、使用shutil
模块的copyfile()
函数将一个空文件复制到原文件,从而清空原文件。
import shutil shutil.copyfile("empty_file.txt", "file.txt")
5、使用os
模块的remove()
函数删除文件,然后重新创建一个空文件。
import os os.remove("file.txt") with open("file.txt", "w") as file: pass