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
Not a complete answer more of an extension to ondra's answer
When using
truncate()
( my preferred method ) make sure your cursor is at the required position. When a new file is opened for reading -open('FILE_NAME','r')
it's cursor is at 0 by default. But if you have parsed the file within your code, make sure to point at the beginning of the file again i.etruncate(0)
By defaulttruncate()
truncates the contents of a file starting from the current cusror position.A simple example
Assigning the file pointer to null inside your program will just get rid of that reference to the file. The file's still there. I think the
remove()
function in the cstdio.h
is what you're looking for there. Not sure about Python.Since text files are sequential, you can't directly erase data on them. Your options are:
Look at the
seek
/truncate
function/method to implement any of the ideas above. Both Python and C have those functions.From user @jamylak an alternative form of
open("filename","w").close()
isIn python:
Or alternatively, if you have already an opened file:
In C++, you could use something similar.
You have to overwrite the file. In C++: