Iterating through directories and removing files based off extensions in Python -


i have file structure emulates following: enter image description here

i have folder, folder contains excel folder , bunch of text documents. each excel folder has bunch of .xlsx files.

this same idea can replicated infinite amount of times following same structure. trying go each excel folder each directory, remove files .xlsx extension , continue process until excel folders have been visited.

this little bit of code failing with:

def clean_out_excel_test_data():     #for each folder in test_log directory         #open each folder             #for each_folder contains word excel                 #open each_folder                     #for each file in each_folder, remove      log_directory = "test_log_data/"      each_folder in sorted(os.listdir(log_directory)):         print each_folder + ' in root'         each_folder2 in sorted(os.listdir('%s/%s'%(log_directory,each_folder))) if os.path.isdir(each_folder2):             print '\t-' + each_folder2 + ' sub-folder'             each_excel_file in sorted(os.listdir('%s/%s/%s'%(log_directory,each_folder, each_folder2))):                 print '\t\t-' + each_excel_file + ' sub excel file' 

i realize code garbage, wanted @ least show going for.

let os.walk handle directory traversal you:

for root, dirs, files in os.walk('/path/to/test_log_data'):     if 'excel' not in root:         continue     fname in files:         if fname.endswith('.xlsx'):             os.remove(os.path.join(root, fname)) 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -