尝试和除了FileNotFoundE外的情况

2024-05-08 22:35:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在设置一个程序来使用指定的文件位置,但希望能够在文件被移动时更改它。我希望程序读取记事本文件,其中包含指向正确文件位置的链接。正如你所看到的,try and except没有像我所希望的那样工作,也不知道为什么。在

这是我的代码:

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

我得到的输出是:

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


Tags: 文件程序readusernameexcelglobalusersflash
1条回答
网友
1楼 · 发布于 2024-05-08 22:35:15

在执行字符串赋值时,FileNotFoundError将不会引发。所以

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

永远不会抛出一个FileNotFoundError。但是,当您打开文件时,可能会发生异常,就像您在这里所做的那样:

^{pr2}$

您需要将对open的调用放在try块中,并在抛出错误时采取相应的操作。在

顺便说一句,我不认为当你运行你发布的代码时,你给出的堆栈跟踪不会发生。但是不管怎样,您希望调用try块中的open:而不是except块。在

编辑(因为代码已更新):

pd.read_excel也会打开一个文件(px.load_workbook也可能会打开)。{cd1>它也能扔。您需要将其放入try块中,如果找不到该文件,则相应地执行相应的操作。这可能是生成已发布堆栈跟踪的原因,因为操作系统找不到的文件名是由filelocation变量给出的。在

相关问题 更多 >

    热门问题