I would like to delete all txt files in my folder. Can you tell me why my code does not work?
import os,shutil
one = 'C:/1'
two = os.listdir(one)
number = 0
for aList in two:
if os.path.isdir(aList):
myDelete = shutil.rmtree('*txt', os.path.join(one, aList))
number += 1
Solved! Go to Solution.
Jayanta has provided a workable solution, but I will elaborate on why your existing code doesn't work. The shutil.rmtree method is designed to remove entire directory trees, not files within directory trees. As the documentation states, "path must point to a directory", which in your case '*txt' is not a valid directory path.
Check the following code
Change the path of the directory as required.
import os
directory = r".\Directory"
files_in_directory = os.listdir(directory)
filtered_files = [file for file in files_in_directory if file.endswith(".txt")]
for file in filtered_files:
path_to_file = os.path.join(directory, file)
os.remove(path_to_file)
Jayanta has provided a workable solution, but I will elaborate on why your existing code doesn't work. The shutil.rmtree method is designed to remove entire directory trees, not files within directory trees. As the documentation states, "path must point to a directory", which in your case '*txt' is not a valid directory path.