Python Forum
Help needed with a "for loop" + error handling
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help needed with a "for loop" + error handling
#1
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
Reply
#2
(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.
tamiri likes this post
Reply
#3
supufsupuflounder,
Thank you for the answer.
It works like a charm :-)
Tamir
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Star python exception handling handling .... with traceback mg24 3 1,283 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  Handling Python Fatal Error richajain1785 7 5,918 Oct-14-2021, 01:34 PM
Last Post: Tails86
  Error Handling JarredAwesome 5 2,940 Oct-17-2020, 12:41 AM
Last Post: JarredAwesome
  Error handling using cmd module leifeng 3 2,898 Jun-06-2020, 06:25 PM
Last Post: leifeng
  Excpetion Handling Getting Error Number gw1500se 4 2,393 May-29-2020, 03:07 PM
Last Post: gw1500se
  Pyhton Coding Help Needed (very small error) friduk 2 2,460 Oct-23-2019, 08:41 AM
Last Post: Gribouillis
  Com Error with macro within for loop due to creating new workbook in the loop Lastwizzle 0 1,371 May-18-2019, 09:29 PM
Last Post: Lastwizzle
  Warning / Error handling in python Prarthana_12 1 5,109 Feb-08-2019, 09:21 PM
Last Post: snippsat
  Help With Error Handling jo15765 6 4,128 Sep-14-2018, 06:27 PM
Last Post: jo15765
  Error Handling/No results from SQL Query JP_ROMANO 7 9,487 Jul-18-2018, 02:31 PM
Last Post: JP_ROMANO

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020