有几种方法可以将文件的逻辑大小设置为0,具体取决于您访问文件的方式:
清空打开的文件:
def deleteContent(pfile):
pfile.seek(0)
pfile.truncate()
@H_403_10@
def deleteContent(fd):
os.ftruncate(fd, 0)
os.lseek(fd, 0, os.SEEK_SET)
@H_403_10@
def deleteContent(fName):
with open(fName, "w"):
pass
@H_403_10@
就是说, 在一般情况下 , 重用 临时文件可能不是有效的,也不是合乎需要的。除非您有非常特定的需求,否则应该考虑使用tempfile.TemporaryFile
和上下文管理器 几乎透明地创建/使用/删除临时文件:
import tempfile
with tempfile.TemporaryFile() as temp:
# do whatever you want with `temp`
# <- `tempfile` guarantees the file being both closed *and* deleted
# on exit of the context manager
@H_403_10@