Delete contents of a file (Truncate File) in Python
This post will discuss how to delete the contents of a file in Python. In order words, truncate the file to 0 bytes.
1. Using 'w' mode
The simplest solution is to open the file in w mode, which opens it for writing. The file is created if it does not exist; otherwise, it is truncated. Here’s what the code would look like:
|
1 2 3 4 5 6 7 |
path = 'some/dir/file.txt' try: open(path, 'w').close() except IOError: print('Failure') |
The above code explicitly closes the file handler with the close() function. This can be avoided using the with statement, which automatically closes the file handler when done with it. Here’s an example of using the with statement:
|
1 2 3 4 5 6 7 8 |
path = 'some/dir/file.txt' try: with open(path, 'w'): pass except IOError: print('Failure') |
2. Using truncate() function
Alternatively, you can open a file for updating (reading and writing) without truncating it. This can be done using the r+ mode, which neither deletes the content nor creates a new file if it doesn’t exist. Then to truncate the file to 0 bytes, use the truncate() function.
|
1 2 3 4 5 6 7 8 |
path = 'some/dir/file.txt' try: with open(path, 'r+') as f: f.truncate() except IOError: print('Failure') |
That’s all about deleting the contents of a file in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)