[英]How to erase the file contents of text file in Python?
I have text file which I want to erase in Python. How do I do that?我在 Python 中有我想删除的文本文件。我该怎么做?
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+
Not a complete answer more of an extension to ondra's answer不是一个完整的答案,更多的是对 ondra 答案的扩展
When using truncate()
( my preferred method ) make sure your cursor is at the required position.使用
truncate()
(我的首选方法)时,请确保光标位于所需位置。 When a new file is opened for reading - open('FILE_NAME','r')
it's cursor is at 0 by default.当打开一个新文件进行读取时 -
open('FILE_NAME','r')
默认情况下,它的光标位于 0。 But if you have parsed the file within your code, make sure to point at the beginning of the file again ie truncate(0)
By default truncate()
truncates the contents of a file starting from the current cusror position.但是,如果您在代码中解析了文件,请确保再次指向文件的开头,即
truncate(0)
默认情况下, truncate()
从当前光标位置开始截断文件的内容。
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) (您应该关闭它,因为文件自动关闭的时间可能是特定于实现的)
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.当使用
with open("myfile.txt", "r+") as my_file:
,我在myfile.txt
得到奇怪的零,特别是因为我首先读取文件。 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)
.为了让它工作,我必须首先使用
my_file.seek(0)
将my_file
的指针更改为文件的开头。 Then I could do my_file.truncate()
to clear the file.然后我可以执行
my_file.truncate()
来清除文件。
来自用户@jamylak 的另一种形式open("filename","w").close()
是
with open('filename.txt','w'): pass
You have to overwrite the file.您必须覆盖该文件。 In C++:
在 C++ 中:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
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.
如果您真的很担心,最好进行零填充并使用像File Shredder或CCleaner这样的专业实用程序来清除驱动器上的“空”空间。
Writing and Reading file content写入和读取文件内容
def writeTempFile(text = None):
filePath = "/temp/file1.txt"
if not text: # If not provided 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它对我有用
You can also use this (based on a few of the above answers):您也可以使用它(基于上面的一些答案):
file = open('filename.txt', 'w')
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!快乐编码!
Since text files are sequential, you can't directly erase data on them.由于文本文件是连续的,您不能直接擦除其中的数据。 Your options are:
您的选择是:
Look at the seek
/ truncate
function/method to implement any of the ideas above.查看
seek
/ truncate
函数/方法来实现上述任何想法。 Both Python and C have those functions. Python 和 C 都有这些功能。
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.
要么满足于覆盖“空”值,要么读取您关心的文件部分并将其写入另一个文件。
Assigning the file pointer to null inside your program will just get rid of that reference to the file.在您的程序中将文件指针分配为 null 只会摆脱对文件的引用。 The file's still there.
文件还在。 I think the
remove()
function in the c stdio.h
is what you're looking for there.我认为 c
stdio.h
的remove()
函数正是您在那里寻找的。 Not sure about Python.不确定 Python。
This is my method:这是我的方法:
r+
moder+
模式打开文件file.read()
file.read()
从文件中读取当前数据file.seek(0)
file.seek(0)
将指针移动到第一行file.truncate(0)
file.truncate(0)
从文件中删除旧数据file.read()
file.read()
保存的内容So full code will look like this:所以完整的代码将如下所示:
with open(file_name, 'r+') as file:
old_data = file.read()
file.seek(0)
file.truncate(0)
file.write('my new content\n')
file.write(old_data)
Because we are using with open
, file will automatically close.因为我们使用
with open
,文件会自动关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.