如何删除python中的文件内容 [英] How to delete only the content of file in python

查看:216
本文介绍了如何删除python中的文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个临时文件,里面有一些内容,一个python脚本生成一些输出到这个文件。我想这个重复N次,所以我需要重用该文件(实际上是文件的数组)。我正在删除整个内容,所以临时文件将在下一个周期中为空。对于删除内容,我使用这段代码:

pre $ def $ deletecontent(pfile)

pfile.seek 0)
pfile.truncate()
pfile.seek(0)#我相信这个寻求是多余的

返回pfile

tempFile = deleteContent( tempFile)

我的问题是:是否有其他(更好,更短或更安全)整个内容没有从磁盘实际删除临时文件?

类似于 tempFile.truncateAll()

解决方案


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



有多种方法可以将文件的逻辑大小设置为0,具体取决于您如何访问该文件:

清空一个打开的文件:

pre $ def $ delete pre $ b $ pfile.seek
pfile .truncate()






文件描述符是已知的:

  def deleteContent(fd):
os.ftruncate(fd,0)
os.lseek(fd,0,os.SEEK_SET)







$ b

  def deleteContent(fName):
with open (fName,w):
pass




我有一个临时文件,需要一些内容重复使用那个文件


就是说,在一般情况下 重新使用一个临时文件。除非你有非常特殊的需求,否则你应该考虑使用 tempfile.TemporaryFile

 <$ c 

with tempfile.TemporaryFile()as temp:
#通过`temp`做任何你想做的事

#< - `tempfile`保证文件被关闭*和*在上下文管理器退出时删除


I have a temporary file with some content and a python script generating some output to this file. I want this to repeat N times, so I need to reuse that file (actually array of files). I'm deleting the whole content, so the temp file will be empty in the next cycle. For deleting content I use this code:

def deleteContent(pfile):

    pfile.seek(0)
    pfile.truncate()
    pfile.seek(0) # I believe this seek is redundant

    return pfile

tempFile=deleteContent(tempFile)

My question is: Is there any other (better, shorter or safer) way to delete the whole content without actually deleting the temp file from disk?

Something like tempFile.truncateAll()?

解决方案

How to delete only the content of file in python

There is several ways of set the logical size of a file to 0, depending how you access that file:

To empty an open file:

def deleteContent(pfile):
    pfile.seek(0)
    pfile.truncate()


To empty a open file whose file descriptor is known:

def deleteContent(fd):
    os.ftruncate(fd, 0)
    os.lseek(fd, 0, os.SEEK_SET)


To empty a closed file (whose name is known)

def deleteContent(fName):
    with open(fName, "w"):
        pass



I have a temporary file with some content [...] I need to reuse that file

That being said, in the general case it is probably not efficient nor desirable to reuse a temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFile and a context manager to almost transparently create/use/delete your temporary files:

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

这篇关于如何删除python中的文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆