Answers:
在python中:
open('file.txt', 'w').close()
或者,如果您已经打开了文件:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
在C ++中,您可以使用类似的东西。
#include<fstream>然后std::ofstream("file.txt");大约和Python一样短。:)
f.seek(0)之后添加f.truncate(0),否则您将在文件的开头添加奇怪的\ x00。
以“写入”模式打开文件会清除该文件,您不必专门写入该文件:
open("filename", "w").close()
(您应该关闭它,因为文件自动关闭的时间可能取决于实现方式)
用户@jamylak的另一种形式open("filename","w").close()是
with open('filename.txt','w'): pass
您必须覆盖文件。在C ++中:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
close()通话。析构函数将关闭文件。因此,您只需要创建一个临时文件:ofstream("test.txt");
在程序中将文件指针分配为null只会摆脱对该文件的引用。该文件仍然存在。我认为remove()c中的功能stdio.h就是您在那儿寻找的。不确定Python。
如果安全性对您很重要,那么打开文件进行写入并再次关闭将是不够的。至少某些信息仍将保留在存储设备上,例如可以通过使用光盘恢复实用程序找到。
例如,假设您要擦除的文件包含生产密码,并且需要在本操作完成后立即删除。
文件使用完毕后,请对其进行零填充,以确保敏感信息被销毁。
在最近的项目中,我们使用了以下代码,该代码非常适合小型文本文件。它用零行覆盖现有内容。
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等专业实用程序擦拭干净驱动器上的“空”空间。
除非需要擦除结尾,否则不能从就地文件“擦除”。要么满足于覆盖“空”值,要么阅读您关心的文件部分并将其写入另一个文件。
由于文本文件是顺序文件,因此您不能直接删除它们上的数据。您的选择是:
查看seek/ truncatefunction / method以实现上述任何想法。Python和C都具有这些功能。
os.remove或os.unlink在python中或unlink在C中使用。另一种选择是重新打开文件以进行写入或使用truncate。
写入和读取文件内容
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
对我有用
您也可以使用此方法(基于上述一些答案):
file = open('filename.txt', 'w')
file.write('')
file.close
当然,这是清除文件的一种非常糟糕的方法,因为它需要很多行代码,但是我只是写了此文件,以向您展示它也可以用此方法完成。
祝您编码愉快!