简体   繁体   English

尝试并除外FileNotFoundError

[英]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. 如您所见,try和except无法正常工作,无法弄清原因。

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' FileNotFoundError:[错误2]没有这样的文件或目录:'\\\\ flash \\ Users \\ Coop \\ Volunteering \\ ProgramReferenceX.xlsx'

A FileNotFoundError will not be raised when doing string assignment. 进行字符串分配时,不会引发FileNotFoundError So, 所以,

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

will never throw a FileNotFoundError . 永远不会抛出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. 您需要将调用opentry块中,并在引发错误时采取相应措施。

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. 但是无论哪种方式,您都希望在try块中open调用:而不是except块。

EDIT (since code's been updated): 编辑(由于代码已更新):

pd.read_excel also opens a file (and px.load_workbook probably does too). pd.read_excel还会打开一个文件(而px.load_workbook可能也会打开)。 It can throw a FileNotFoundError as well. 它也可以抛出FileNotFoundError You'll want to put it in the try block and act accordingly if the file can't be found. 您将需要将其放在try块中,如果找不到该文件,则应采取相应的措施。 This is probably what generated the posted stack trace since the filename your OS can't find is given by the filelocation variable. 这可能是生成发布的堆栈跟踪的原因,因为OS找不到的文件名是由filelocation变量给出的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM