我有一个文本文件,我想在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都有这些函数。

其他回答

由于文本文件是顺序的,所以不能直接擦除其中的数据。你的选择是:

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都有这些函数。

你也可以使用这个(基于上面的一些答案):

file = open('filename.txt', 'w')
file.close()

当然,这是一种非常糟糕的清除文件的方式,因为它需要很多行代码,但我只是写这个来告诉你们,它也可以在这个方法中完成。

编码快乐!

除非需要删除文件的结尾,否则不能就地“擦除”文件。要么满足于覆盖一个“空”值,要么读取文件中您关心的部分并将其写入另一个文件。

当使用open("myfile.txt", "r+")作为my_file:时,我在myfile.txt中得到奇怪的0,特别是因为我先读取文件。为了让它工作,我必须首先用my_file.seek(0)将my_file的指针更改为文件的开头。然后我可以执行my_file.truncate()来清除文件。

如果安全性对您来说很重要,那么打开文件进行写入并再次关闭它是不够的。至少一些信息仍然在存储设备上,并且可以被找到,例如,通过使用磁盘恢复工具。

例如,假设您正在擦除的文件包含生产密码,需要在当前操作完成后立即删除。

一旦你使用完文件,就对它进行零填充,这有助于确保敏感信息被销毁。

在最近的一个项目中,我们使用了下面的代码,它可以很好地处理小文本文件。它用零行覆盖现有内容。

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来清除驱动器上的“空”空间。