Delete

380
2
Jump to solution
03-21-2021 03:02 AM
Mick
by
New Contributor

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

0 Kudos
1 Solution

Accepted Solutions
JoshuaBixby
MVP Esteemed Contributor

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.

View solution in original post

2 Replies
JayantaPoddar
MVP Esteemed Contributor

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)

  



Think Location
JoshuaBixby
MVP Esteemed Contributor

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.