0
How do I clear a file using Python ?
Hey, I know the basics of File handling as of now, I wan't to make a project tho, I needs to replace the contents of a file with something stored in a variable, say text. So the question is how do I clear all the contents of the file using file handling in Python?
4 Respuestas
+ 5
Yash Thale ,
an other method to clear a file is by using the truncate() method of the file object.
this method can be particularly useful if the file is already opened (in 'r+' mode) and we want to clear its content without closing and reopening it again.
i personally do not find it entirely obvious, to open a file in a specific mode ('w') in order to delete its content.
path = '/storage/emulated/0/_python codes pydroid/'
with open(path + 'sample.txt', 'r+') as file:
for line in file: # do domething here ...
print(line)
file.truncate(0) # clearing the file
print('file content has been cleared.')
do something here ...
+ 4
When you open a file and use the "w" (write) file mode, the original contents of the file get deleted and it starts over as an empty, zero-length file.
+ 2
Yash Thale you're welcome!
0
Brian Thank You Really, That's a tool I want to create for my AI application idea 😅