Python File truncate() MethodThe truncate() method resizes the file to the given number of bytes. If the size is not specified, the current position will be used.
remove() method in Python can be used to remove files, and the os. rmdir() method can be used to delete an empty folder. The shutil. rmtree() method can be used to delete a folder along with all of its files.
In python:
open('file.txt', 'w').close()
Or alternatively, if you have already an opened file:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
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.e truncate(0)
By default truncate()
truncates the contents of a file starting from the current cusror position.
A simple example
Opening a file in "write" mode clears it, you don't specifically have to write to it:
open("filename", "w").close()
(you should close it as the timing of when the file gets closed automatically may be implementation specific)
As @jamylak suggested, a good alternative that includes the benefits of context managers is:
with open('filename.txt', 'w'):
pass
When using with open("myfile.txt", "r+") as my_file:
, I get strange zeros in myfile.txt
, especially since I am reading the file first. For it to work, I had to first change the pointer of my_file
to the beginning of the file with my_file.seek(0)
. Then I could do my_file.truncate()
to clear the file.
You have to overwrite the file. In C++:
#include <fstream>
std::ofstream("test.txt", std::ios::out).close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With