s_mj
s_mj

Reputation: 580

failing to move file from input folder to error folder

I am trying to run a code where i am read files sheets. Issue i am facing is, if there is a file which has no sheet named SheetSum I am not able to move it to error location.

example:

def read_file(data_file):
    # data_file = '\rr\ex.xlsx'
    sheets = {}
    try:
        print("Reading file: "+data_file)
        sheets['df_1'] = pd.read_excel(open(data_file,'rb'), 'SheetSum')
    except Exception as excpt:
        print("Exception occurred", exc_info=True)
    return sheets

read_file(file)
shutil.move( file, dirpath +'\\processed_files')

Getting an error as:

[WinError 32] The process cannot access the file because it is being used by another process

Updates:

If finally is present, it specifies a cleanup handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception it is re-raised at the end of the finally clause. If the finally clause raises another exception, the saved exception is set as the context of the new exception.

..More Here

Accepted Solution worked like charm.

Upvotes: 0

Views: 317

Answers (1)

Axe319
Axe319

Reputation: 4365

Try closing the file before attempting to move it. So something like

def read_file(data_file):
    # data_file = '\rr\ex.xlsx'
    sheets = {}
    try:
        print("Reading file: "+data_file)
        sheets_file = open(data_file,'rb')
        sheets['df_1'] = pd.read_excel(sheets_file, 'SheetSum')
    except Exception as excpt:
        print("Exception occurred", exc_info=True)
    finally:
        sheets_file.close()
    return sheets

read_file(file)
shutil.move( file, dirpath +'\\processed_files')

The problem is the file opens, is handed to the pandas method, and when an exception occurs, your file is never closed.

Adding a finally to your try except block ensures that your file is always closed.

Upvotes: 1

Related Questions