FanMan
FanMan

Reputation: 160

Try and Except FileNotFoundError

I am setting up a program to use a specified file location but want to be able to change it if the file gets moved. I want the program to read the notepad file which contains the link to the correct file location. As you can see, the try and except is not working as I would like it to and can't figure out why.

Here is my code:

def hours():

    #getting username
    global username
    username = getpass.getuser() 

    #defining excel location
    try:
        global filelocation
        filelocation = r'\\flash\Users\Coop\Volunteering\ProgramReferenceX.xlsx'
    except FileNotFoundError:
        global desktop
        desktop = r'C:\Users\\' + username + '\Desktop\Filelocation.txt'
        filelocationtext = open(desktop,'r')
        filelocation = filelocationtext.read()


    global filelog
    filelog=pd.read_excel(filelocation ,read_only=True, sheetname=None, na_filter=False)


    #setting password
    global passwordx

    logbook=pxl.load_workbook(filelocation, data_only=False)
    ashx=logbook['datasheet']

    passwordx = ashx.cell(row=16, column=15).value

What I get as an output is:

FileNotFoundError: [Errno 2] No such file or directory: '\\flash\Users\Coop\Volunteering\ProgramReferenceX.xlsx'

Upvotes: 1

Views: 3926

Answers (1)

Matt Messersmith
Matt Messersmith

Reputation: 13747

A FileNotFoundError will not be raised when doing string assignment. So,

global filelocation
filelocation = r'\\flash\Users\Coop\Volunteering\ProgramReferenceX.xlsx'

will never throw a FileNotFoundError. The exception may occur, though, when you are opening a file, like you're doing here:

filelocationtext = open(desktop,'r')

You need to put the call to open in the try block, and act accordingly if the error is thrown.

Btw, I don't think the stack trace you gave can happen when you run your posted code. But either way, you want the call to open in the try block: not the except block.

EDIT (since code's been updated):

pd.read_excel also opens a file (and px.load_workbook probably does too). It can throw a FileNotFoundError as well. You'll want to put it in the try block and act accordingly if the file can't be found. This is probably what generated the posted stack trace since the filename your OS can't find is given by the filelocation variable.

Upvotes: 2

Related Questions