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)
我认为最简单的方法是简单地以写入模式打开文件,然后将其关闭。例如,如果您的文件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)