您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何仅删除python中文件的内容

如何仅删除python中文件的内容

如何仅删除python中文件内容

有几种方法可以将文件的逻辑大小设置为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@
python 2022/1/1 18:27:26 有432人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶