我有一个文本文件,我想在Python中擦除。我怎么做呢?
当前回答
由于文本文件是顺序的,所以不能直接擦除其中的数据。你的选择是:
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.
看看seek/truncate函数/方法来实现上面的任何想法。Python和C都有这些函数。
其他回答
正如@jamylak所建议的,包含上下文管理器优点的一个好的替代方案是:
with open('filename.txt', 'w'):
pass
这是我的方法:
使用r+模式打开文件 使用file. Read()从文件中读取当前数据 使用file.seek(0)将指针移到第一行 使用file.truncate(0)从文件中删除旧数据 先写新内容,再写之前用file.read()保存的内容
所以完整的代码是这样的:
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)
因为我们使用的是打开,文件会自动关闭。
这不是一个完整的答案,更多的是对ondra答案的延伸
当使用truncate()(我的首选方法)时,确保您的光标位于所需的位置。 当打开一个新文件进行读取时- open('FILE_NAME','r'),它的光标默认为0。 但如果你在代码中解析了文件,请确保再次指向文件的开头,即truncate(0) 默认情况下,truncate()从当前cusror位置开始截断文件的内容。
一个简单的例子
你必须覆盖这个文件。在c++中:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
如果安全性对您来说很重要,那么打开文件进行写入并再次关闭它是不够的。至少一些信息仍然在存储设备上,并且可以被找到,例如,通过使用磁盘恢复工具。
例如,假设您正在擦除的文件包含生产密码,需要在当前操作完成后立即删除。
一旦你使用完文件,就对它进行零填充,这有助于确保敏感信息被销毁。
在最近的一个项目中,我们使用了下面的代码,它可以很好地处理小文本文件。它用零行覆盖现有内容。
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来清除驱动器上的“空”空间。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录