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?

18th May 2025, 3:49 PM
Yash Thale
Yash Thale - avatar
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 ...
19th May 2025, 7:52 PM
Lothar
Lothar - avatar
+ 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.
18th May 2025, 4:37 PM
Brian
Brian - avatar
+ 2
Yash Thale you're welcome!
18th May 2025, 7:12 PM
Brian
Brian - avatar
0
Brian Thank You Really, That's a tool I want to create for my AI application idea 😅
18th May 2025, 5:35 PM
Yash Thale
Yash Thale - avatar
OSZAR »