Python Forum
Help needed with a "for loop" + error handling - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Help needed with a "for loop" + error handling (/thread-37320.html)



Help needed with a "for loop" + error handling - tamiri - May-27-2022

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:

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



RE: Help needed with a "for loop" + error handling - supuflounder - May-27-2022

(May-27-2022, 11:28 AM)tamiri Wrote: 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:

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()
    #***************************
    latest_file = ''
    #****************************
    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  #  Eliminate this line
        #*************************
    except:
        print("{}{}{}".format('Folder: ',folder,' not found'))
        #**********************************
        continue
        #**********************************

    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
I suggest adding the lines I showed in #**** comments in the above code. And delete the break, which makes no sense. That just stops the loop, but the code below is not executed at all (the code that wants to use latest_file). It only gets executed if the try code throws an exception, which I suspect is not what you want at all. What this code does is stop the loop without doing anything if the try does not throw an exception, and try to execute the code if the try fails

Note that the code that follows the except is still part of your for-loop. This suggests that you want it to execute each time the loop succeeds in doing the try code.

The problem is that latest_file not created until it is assigned to. But if any computation in the try fails before the assignment, then the name is not defined, and that is what is happening to you.

If you make an assignment outside the try, then the name will be defined, and have the value of the empty string, even if the exception happens before the inner assignment.

Then, your except clause does a printout, but what happens next? You fall down into the code below it, for which the values are not defined. By adding the continue, you force the loop to iterate.


RE: Help needed with a "for loop" + error handling - tamiri - May-27-2022

supufsupuflounder,
Thank you for the answer.
It works like a charm :-)
Tamir