Sometimes there are situations when you want to write to a file which already contains data. Or just delete all the contents. Let’s see how to clean this file with Python 3.
You can clean up a file in Python 3 in the following ways:
- When opening, use the mode in which the pointer is at the beginning of the document.
- Manually move the pointer to the start position.
- Use the means of the operating system to zero the contents of the file.
Let’s look at these options in detail.
When a file is opened for writing, the pointer to the current position in the document can be located at the beginning or at the end of the document. If the pointer is at the end, the data will be overwritten. We are interested in the variant when the pointer is located at the beginning.
f = open('test.txt', 'w') f.close()
Here w specifies the mode of opening the file for writing in text mode with the pointer placed at the beginning. After executing this code, if the specified file existed, its contents will be cleared. If it didn’t exist, a new empty one will be created. Before closing, information could be added. It will be written from the beginning of the file, not added to the end.
f = open('test.txt', 'w') f.write('something') f.close()
If you want to write data to a binary file, you should use “wb” mode. If it is the other way around, we need to add information to the end of the file. At the same time the old data should remain. In this case we should add the symbol + to the mode. The mode of opening a text document will be “w+”, and binary “wb+”. More information on opening modes can be found in a separate article on our site.
Moving the pointer
If we open a file for writing and we don’t know where the pointer is. Perhaps we have already written some data. We can just move the pointer to the beginning and close it. In this case, the document will be empty.
f = open('test.txt', 'w+') f.seek(0) f.close()
In this example, the opening was done intentionally in overwrite mode. After closing, even if there was data in the file, it will be deleted. Here is another example, here we write data, then move pointer to the beginning. After that we write it down again. As a result, at the end of the work, the file will contain only the last record made. The data that was entered at the beginning will be safely deleted.
f = open('test.txt', 'w+') f.write('something string') f.seek(0) f.write('new string') f.close()
Using the operating system tools
To clean it up through the operating system, we use the standard library os. First of all, it has to be connected using the import os instruction. On linux it should go like this.
import os os.system(r' >file.txt')
You can use the commands cp or cat. Here is an example of a solution with cat.
If the code is running on Windows, the solution could be this: