May-27-2022, 11:28 AM
I would like to iterate over a list of items.
In each round, Python is checking the latest Excel file in a folder, opens it, and saves it.
Upon an error, I would like Python to print that the folder was not found and to continue to the next round of iteration.
I understand why I get the error...but I don't know how to arrange the code to fix it.
My code:
In each round, Python is checking the latest Excel file in a folder, opens it, and saves it.
Upon an error, I would like Python to print that the folder was not found and to continue to the next round of iteration.
I understand why I get the error...but I don't know how to arrange the code to fix it.
My code:
from openpyxl import Workbook, load_workbook import time import glob import os from time import sleep import sys test_list = [ 'C:/test/folder1/', 'C:/test/folder2/', 'C:/test/folder3/' ] for i in range(len(test_list)): print(test_list[i]) sleep(1) start = time.time() try: folder=test_list[i] list_of_files = glob.glob(folder+'*.xlsx') # getting the files in the folder latest_file = max(list_of_files, key=os.path.getctime) # getting the latest file from the list of files break except: print("{}{}{}".format('Folder: ',folder,' not found')) print("{}{}".format('Opening Workbook: ',latest_file)) wb = load_workbook(latest_file) #openning the file wb.save(latest_file) #saving and closing the file end = time.time() print("{}{}{}{:.0f}{}".format('Workbook ',latest_file,' resaved after ',end-start,' seconds'))The Output / Traceback I get:
Output:C:/test/folder1/
Folder: C:/test/folder1/ not found
Traceback (most recent call last):
File "c:/Python-Excel/resaving SAP Excels with a loop.py", line 58, in <module>
print("{}{}".format('Opening Workbook: ',latest_file))
NameError: name 'latest_file' is not defined