问题:如何在Python中清除文本文件的文件内容?
I have text file which I want to erase in Python. How do I do that?
回答 0
在python中:
open('file.txt', 'w').close()
或者,如果您已经打开了文件:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
在C ++中,您可以使用类似的东西。
In python:
open('file.txt', 'w').close()
Or alternatively, if you have already an opened file:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
In C++, you could use something similar.
回答 1
不是完整的答案,更多是对ondra答案的扩展
使用truncate()
(我的首选方法)时,请确保光标位于所需位置。当打开一个新文件进行读取时- open('FILE_NAME','r')
默认情况下,其光标为0。但是,如果您已经在代码中解析了该文件,请确保再次指向该文件的开头,即truncate(0)
默认情况下truncate()
,将从当前cusror位置开始截断文件的内容。
一个简单的例子
Not a complete answer more of an extension to ondra’s answer
When using truncate()
( my preferred method ) make sure your cursor is at the required position.
When a new file is opened for reading – open('FILE_NAME','r')
it’s cursor is at 0 by default.
But if you have parsed the file within your code, make sure to point at the beginning of the file again i.e truncate(0)
By default truncate()
truncates the contents of a file starting from the current cusror position.
A simple example
回答 2
以“写入”模式打开文件会清除该文件,您不必专门写入该文件:
open("filename", "w").close()
(您应该关闭它,因为文件自动关闭的时间可能取决于实现方式)
Opening a file in “write” mode clears it, you don’t specifically have to write to it:
open("filename", "w").close()
(you should close it as the timing of when the file gets closed automatically may be implementation specific)
回答 3
用户@jamylak的另一种形式open("filename","w").close()
是
with open('filename.txt','w'): pass
From user @jamylak an alternative form of open("filename","w").close()
is
with open('filename.txt','w'): pass
回答 4
使用时with open("myfile.txt", "r+") as my_file:
,在中会出现奇怪的零myfile.txt
,尤其是因为我先读取文件时。为了使其正常工作,我首先必须使用来更改my_file
文件开头的指针my_file.seek(0)
。然后,我可以my_file.truncate()
清除文件。
When using with open("myfile.txt", "r+") as my_file:
, I get strange zeros in myfile.txt
, especially since I am reading the file first. For it to work, I had to first change the pointer of my_file
to the beginning of the file with my_file.seek(0)
. Then I could do my_file.truncate()
to clear the file.
回答 5
您必须覆盖文件。在C ++中:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
You have to overwrite the file. In C++:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
回答 6
在程序中将文件指针分配为null只会摆脱对该文件的引用。该文件仍然存在。我认为remove()
c中的功能stdio.h
就是您在那儿寻找的。不确定Python。
Assigning the file pointer to null inside your program will just get rid of that reference to the file. The file’s still there. I think the remove()
function in the c stdio.h
is what you’re looking for there. Not sure about Python.
回答 7
如果安全性对您很重要,那么打开文件进行写入并再次关闭将是不够的。至少某些信息仍将保留在存储设备上,例如可以通过使用光盘恢复实用程序找到。
例如,假设您要擦除的文件包含生产密码,并且需要在本操作完成后立即删除。
文件使用完毕后,请对其进行零填充,以确保敏感信息被销毁。
在最近的项目中,我们使用了以下代码,该代码非常适合小型文本文件。它用零行覆盖现有内容。
import os
def destroy_password_file(password_filename):
with open(password_filename) as password_file:
text = password_file.read()
lentext = len(text)
zero_fill_line_length = 40
zero_fill = ['0' * zero_fill_line_length
for _
in range(lentext // zero_fill_line_length + 1)]
zero_fill = os.linesep.join(zero_fill)
with open(password_filename, 'w') as password_file:
password_file.write(zero_fill)
请注意,零填充不能保证您的安全。如果您真的很担心,最好将其填充为零,并使用File Shredder或CCleaner等专业实用程序擦拭干净驱动器上的“空”空间。
If security is important to you then opening the file for writing and closing it again will not be enough. At least some of the information will still be on the storage device and could be found, for example, by using a disc recovery utility.
Suppose, for example, the file you’re erasing contains production passwords and needs to be deleted immediately after the present operation is complete.
Zero-filling the file once you’ve finished using it helps ensure the sensitive information is destroyed.
On a recent project we used the following code, which works well for small text files. It overwrites the existing contents with lines of zeros.
import os
def destroy_password_file(password_filename):
with open(password_filename) as password_file:
text = password_file.read()
lentext = len(text)
zero_fill_line_length = 40
zero_fill = ['0' * zero_fill_line_length
for _
in range(lentext // zero_fill_line_length + 1)]
zero_fill = os.linesep.join(zero_fill)
with open(password_filename, 'w') as password_file:
password_file.write(zero_fill)
Note that zero-filling will not guarantee your security. If you’re really concerned, you’d be best to zero-fill and use a specialist utility like File Shredder or CCleaner to wipe clean the ’empty’ space on your drive.
回答 8
除非需要擦除结尾,否则不能从就地文件“擦除”。要么满足于覆盖“空”值,要么阅读您关心的文件部分并将其写入另一个文件。
You cannot “erase” from a file in-place unless you need to erase the end. Either be content with an overwrite of an “empty” value, or read the parts of the file you care about and write it to another file.
回答 9
由于文本文件是顺序文件,因此您不能直接删除它们上的数据。您的选择是:
- 最常见的方法是创建一个新文件。从原始文件读取并将所有内容写入新文件,但要擦除的部分除外。写入所有文件后,删除旧文件并重命名新文件,使其具有原始名称。
- 您也可以从要更改的位置开始截断并重写整个文件。试图指出要更改的地方,然后将其余文件读到内存中。找回同一点,截断文件,然后写回内容而没有要删除的部分。
- 另一个简单的选择是用相同长度的另一个数据覆盖数据。为此,寻找确切位置并写入新数据。限制是它必须具有完全相同的长度。
查看seek
/ truncate
function / method以实现上述任何想法。Python和C都具有这些功能。
Since text files are sequential, you can’t directly erase data on them. Your options are:
- The most common way is to create a new file. Read from the original file and write everything on the new file, except the part you want to erase. When all the file has been written, delete the old file and rename the new file so it has the original name.
- You can also truncate and rewrite the entire file from the point you want to change onwards. Seek to point you want to change, and read the rest of file to memory. Seek back to the same point, truncate the file, and write back the contents without the part you want to erase.
- Another simple option is to overwrite the data with another data of same length. For that, seek to the exact position and write the new data. The limitation is that it must have exact same length.
Look at the seek
/truncate
function/method to implement any of the ideas above. Both Python and C have those functions.
回答 10
写入和读取文件内容
def writeTempFile(text = ''):
filePath = "/temp/file1.txt"
if not text: # If blank return file content
f = open(filePath, "r")
slug = f.read()
return slug
else:
f = open(filePath, "a") # Create a blank file
f.seek(0) # sets point at the beginning of the file
f.truncate() # Clear previous content
f.write(text) # Write file
f.close() # Close file
return text
对我有用
Writing and Reading file content
def writeTempFile(text = ''):
filePath = "/temp/file1.txt"
if not text: # If blank return file content
f = open(filePath, "r")
slug = f.read()
return slug
else:
f = open(filePath, "a") # Create a blank file
f.seek(0) # sets point at the beginning of the file
f.truncate() # Clear previous content
f.write(text) # Write file
f.close() # Close file
return text
It Worked for me
回答 11
您也可以使用此方法(基于上述一些答案):
file = open('filename.txt', 'w')
file.write('')
file.close
当然,这是清除文件的一种非常糟糕的方法,因为它需要很多行代码,但是我只是写了此文件,以向您展示它也可以用此方法完成。
祝您编码愉快!
You can also use this (based on a few of the above answers):
file = open('filename.txt', 'w')
file.write('')
file.close()
of course this is a really bad way to clear a file because it requires so many lines of code, but I just wrote this to show you that it can be done in this method too.
happy coding!