In the Unix shell I can do this to empty a file:
cd /the/file/directory/
:> thefile.ext
How would I go about doing this in Python?
Is os.system
the way here, I wouldn't know how since I would have to send 2 actions after each other i.e. the cd
and then the :>
.
The simplest way to delete a file is to use open() and assign it to a new variable in write mode. The Python with statement simplifies exception handling. Using with to open a file in write mode will also clear its data. A pass statement completes the example.
os. remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.
Opening a file creates it and (unless append ('a') is set) overwrites it with emptyness, such as this:
open(filename, 'w').close()
Alternate form of the answer by @rumpel
with open(filename, 'w'): pass
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