Python – How to delete all text files in a given directory
Question:
I would Like a way to delete all text files in a directory. There are other files in the directory as well so I would only like to delete the .txt
files. How would I do this?
Answers:
for file in os.listdir(dir):
if file.endswith('.txt'):
os.remove(os.path.join(dir, file))
EDIT: For clarity, fill in your own dir
name — do not use dir
as variable names.
I would Like a way to delete all text files in a directory. There are other files in the directory as well so I would only like to delete the .txt
files. How would I do this?
for file in os.listdir(dir):
if file.endswith('.txt'):
os.remove(os.path.join(dir, file))
EDIT: For clarity, fill in your own dir
name — do not use dir
as variable names.