我正在设置一个程序来使用指定的文件位置,但希望能够在文件被移动时更改它。我希望程序读取记事本文件,其中包含指向正确文件位置的链接。正如你所看到的,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'
在执行字符串赋值时,
FileNotFoundError
将不会引发。所以永远不会抛出一个
^{pr2}$FileNotFoundError
。但是,当您打开文件时,可能会发生异常,就像您在这里所做的那样:您需要将对
open
的调用放在try
块中,并在抛出错误时采取相应的操作。在顺便说一句,我不认为当你运行你发布的代码时,你给出的堆栈跟踪不会发生。但是不管怎样,您希望调用
try
块中的open
:而不是except
块。在编辑(因为代码已更新):
pd.read_excel
也会打开一个文件(px.load_workbook
也可能会打开)。{cd1>它也能扔。您需要将其放入try
块中,如果找不到该文件,则相应地执行相应的操作。这可能是生成已发布堆栈跟踪的原因,因为操作系统找不到的文件名是由filelocation
变量给出的。在相关问题 更多 >
编程相关推荐