如何在python中只删除文件的内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17126037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to delete only the content of file in python
提问by bartimar
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:
我有一个包含一些内容的临时文件和一个生成该文件的一些输出的 python 脚本。我希望这重复 N 次,所以我需要重用该文件(实际上是文件数组)。我正在删除整个内容,因此临时文件在下一个循环中将为空。为了删除内容,我使用以下代码:
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()?
像tempFile.truncateAll()什么?
采纳答案by Sylvain Leroux
How to delete only the content of file in python
如何在python中只删除文件的内容
There is several ways of set the logical size of a file to 0, depending how you access that file:
有几种方法可以将文件的逻辑大小设置为 0,具体取决于您访问该文件的方式:
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 filewith some content [...] I need to reusethat file
我有一个包含一些内容的临时文件[...] 我需要重用该文件
That being said, in the general caseit is probably not efficient nor desirable to reusea temporary file. Unless you have very specific needs, you should think about using tempfile.TemporaryFileand a context managerto almost transparently create/use/delete your temporary files:
话虽如此,在一般情况下,重用临时文件可能既不高效也不可取。除非你有非常特殊的需求,你应该考虑使用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
回答by dawg
What could be easier than something like this:
有什么比这样的事情更容易:
import tempfile
for i in range(400):
with tempfile.TemporaryFile() as tf:
for j in range(1000):
tf.write('Line {} of file {}'.format(j,i))
That creates 400 temp files and writes 1000 lines to each temp file. It executes in less than 1/2 second on my unremarkable machine. Each temp file of the total is created and deleted as the context manager opens and closes in this case. It is fast, secure, and cross platform.
这将创建 400 个临时文件并向每个临时文件写入 1000 行。它在我不起眼的机器上执行不到 1/2 秒。在这种情况下,上下文管理器在打开和关闭时会创建和删除总数中的每个临时文件。它快速、安全且跨平台。
Using tempfileis a lot better than trying to reinvent it.
使用tempfile比尝试重新发明它要好得多。
回答by the wolf
You can do this:
你可以这样做:
def deleteContent(pfile):
fn=pfile.name
pfile.close()
return open(fn,'w')
回答by Peaceful
I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.datcontains:
我认为最简单的方法是以写模式打开文件然后关闭它。例如,如果您的文件myfile.dat包含:
"This is the original content"
Then you can simply write:
然后你可以简单地写:
f = open('myfile.dat', 'w')
f.close()
This would erase all the content. Then you can write the new content to the file:
这将删除所有内容。然后您可以将新内容写入文件:
f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()

