我有一个文本文件,我想在Python中擦除。我怎么做呢?


当前回答

写入和读取文件内容

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

这对我很有效

其他回答

这不是一个完整的答案,更多的是对ondra答案的延伸

当使用truncate()(我的首选方法)时,确保您的光标位于所需的位置。 当打开一个新文件进行读取时- open('FILE_NAME','r'),它的光标默认为0。 但如果你在代码中解析了文件,请确保再次指向文件的开头,即truncate(0) 默认情况下,truncate()从当前cusror位置开始截断文件的内容。

一个简单的例子

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

file = open('filename.txt', 'w')
file.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来清除驱动器上的“空”空间。

你必须覆盖这个文件。在c++中:

#include <fstream>

std::ofstream("test.txt", std::ios::out).close();

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