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

bar*_*mar 35 python file-io seek

我有一个包含一些内容的临时文件和一个生成此文件的输出的python脚本.我想要重复N次,所以我需要重用该文件(实际上是文件数组).我正在删除整个内容,因此临时文件将在下一个周期中为空.要删除内容,请使用以下代码:

def deleteContent(pfile):

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

    return pfile

tempFile=deleteContent(tempFile)
Run Code Online (Sandbox Code Playgroud)

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

有点像tempFile.truncateAll()

Syl*_*oux 74

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

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

要清空打开的文件:

def deleteContent(pfile):
    pfile.seek(0)
    pfile.truncate()
Run Code Online (Sandbox Code Playgroud)

要清空其文件描述符已知的打开文件:

def deleteContent(fd):
    os.ftruncate(fd, 0)
    os.lseek(fd, 0, os.SEEK_SET)
Run Code Online (Sandbox Code Playgroud)

清空已关闭的文件(其名称已知)

def deleteContent(fName):
    with open(fName, "w"):
        pass
Run Code Online (Sandbox Code Playgroud)



我有一个包含一些内容的临时文件 [...]我需要重用该文件

话虽如此,在一般情况下,重用临时文件可能效率不高,也不可取.除非您有非常具体的需求,否则您应该考虑使用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
Run Code Online (Sandbox Code Playgroud)

  • 来自http://docs.python.org/2/library/stdtypes.html#file.truncate`请注意,如果指定的大小超过文件的当前大小,则结果取决于平台:可能包括文件可能保持不变,增加到指定的大小,就像零填充一样,或者使用未定义的新内容增加到指定的大小."这就是为什么我没有这样做. (2认同)
  • @SylvainLeroux无论哪种方式,我都会得到前导NULL。Linux仍然会忽略`b`标志。来自[`fopen(3)`](http://linux.die.net/man/3/fopen)...“模式字符串也可以包含字母'b'作为最后一个字符或字符在上述任何两个字符的字符串中的字符之间。这完全是为了与C89兼容,并且无效;在包括Linux在内的所有符合POSIX的系统上,“ b”都会被忽略。 (2认同)

Pea*_*ful 7

我认为最简单的方法是简单地以写入模式打开文件,然后将其关闭。例如,如果您的文件myfile.dat包含:

"This is the original content"
Run Code Online (Sandbox Code Playgroud)

然后,您可以简单地编写:

f = open('myfile.dat', 'w')
f.close()
Run Code Online (Sandbox Code Playgroud)

这将删除所有内容。然后,您可以将新内容写入文件:

f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()
Run Code Online (Sandbox Code Playgroud)