Home > Article > Backend Development > How to delete txt files in python
How to delete txt files in python? Let me introduce the basic steps:
If there is a tt text file under the d drive, we To delete it
First introduce the os module
import os
Related recommendations: "python video tutorial"
Use Use the remove command under os to delete the file. The parameter is r'd:/tt.txt'. Usually the path string is r string
os.remove(r'd:/tt.txt')
Now the changed file has been deleted. Now Let’s run the command again and see if there are any errors.
import os os.remove(r'd:/tt.txt') os.remove(r'd:/tt.txt')
This is the error that is prompted. In order to write a more robust program, we usually need to check the file before deleting it. does it exist.
Use the path.exists command to check whether the file exists. The parameter is still the path string
os.path.exists(r'd:/tt.txt') False
With the if statement, we can write a robust command to delete files.
if os.path.exists(r'd:/tt.txt'):os.remove(r'd:/tt.txt')
The above is the detailed content of How to delete txt files in python. For more information, please follow other related articles on the PHP Chinese website!