I have text file which I want to erase in Python. How do I do that?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
When using
with open("myfile.txt", "r+") as my_file:
, I get strange zeros inmyfile.txt
, especially since I am reading the file first. For it to work, I had to first change the pointer ofmy_file
to the beginning of the file withmy_file.seek(0)
. Then I could domy_file.truncate()
to clear the file.Opening a file in "write" mode clears it, you don't specifically have to write to it:
(you should close it as the timing of when the file gets closed automatically may be implementation specific)
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.
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.
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.