python try /除了似乎与KeyError配合使用
尽管我已经使用了尝试/除了数百次以外的条款,但我以前从未见过这样的行为,现在我感到困惑。我可以知道我想念什么吗?
import pandas as pd
import os
season_ep = {}
for season in range(1, 16):
for ind, row in pd.read_html('https://thetvdb.com/series/curious-george/seasons/official/%d' % season)[0].iterrows():
season_ep[row['Name']] = row['Unnamed: 0']
errors = []
for root, dirs, files in os.walk("/run/user/1000/gvfs/smb-share:server=nas.local,share=media/TV Shows/Curious George", topdown=False):
for name in files:
try:
to_print = season_ep[name.split('-')[-1][:-4]]
print(to_print)
except KeyError:
errors.append(os.path.join(dirs, name))
for e in errors:
print('ERROR: %s' % e)
基本上,我正在搜索键'旧麦格吉(McGeorgie)在字典
season_ep 中返回keyError
,但我不' t了解为什么我会收到以下错误。我希望零件除零件以识别
keyError
并接管,并允许代码完全执行。
Traceback (most recent call last):
File "/home/jthom/PycharmProjects/TVDB_ID/main.py", line 14, in <module>
to_print = season_ep[name.split('-')[-1][:-4]]
KeyError: 'Old McGeorgie Had a Farm'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.10/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/snap/pycharm-community/278/plugins/python-ce/helpers/pydev/_pydev_bundle/pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "/snap/pycharm-community/278/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/jthom/PycharmProjects/TVDB_ID/main.py", line 17, in <module>
errors.append(os.path.join(dirs, name))
File "/usr/lib/python3.10/posixpath.py", line 76, in join
a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not list
我正在Ubuntu 22.04上运行Python 3.10.4。感谢您的帮助!
Although I've used try/except clauses hundreds of times, I have never seen behavior like this before and I am baffled right now. May I know what am I missing please?
import pandas as pd
import os
season_ep = {}
for season in range(1, 16):
for ind, row in pd.read_html('https://thetvdb.com/series/curious-george/seasons/official/%d' % season)[0].iterrows():
season_ep[row['Name']] = row['Unnamed: 0']
errors = []
for root, dirs, files in os.walk("/run/user/1000/gvfs/smb-share:server=nas.local,share=media/TV Shows/Curious George", topdown=False):
for name in files:
try:
to_print = season_ep[name.split('-')[-1][:-4]]
print(to_print)
except KeyError:
errors.append(os.path.join(dirs, name))
for e in errors:
print('ERROR: %s' % e)
basically, I'm searching for the key 'Old McGeorgie Had a Farm'
in the dictionary season_ep
which returns a KeyError
, but I don't understand why I'm receiving the following error. I would expect the except
part to recognize the KeyError
and take over, allowing the code to execute fully.
Traceback (most recent call last):
File "/home/jthom/PycharmProjects/TVDB_ID/main.py", line 14, in <module>
to_print = season_ep[name.split('-')[-1][:-4]]
KeyError: 'Old McGeorgie Had a Farm'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3.10/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/snap/pycharm-community/278/plugins/python-ce/helpers/pydev/_pydev_bundle/pydev_umd.py", line 198, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "/snap/pycharm-community/278/plugins/python-ce/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/home/jthom/PycharmProjects/TVDB_ID/main.py", line 17, in <module>
errors.append(os.path.join(dirs, name))
File "/usr/lib/python3.10/posixpath.py", line 76, in join
a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not list
I'm running Python 3.10.4 on Ubuntu 22.04. Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您仔细查看堆栈跟踪,您将看到此片段:
在处理上述异常时,发生了另一个例外
。这告诉您上述keyError
被捕获了,但是在execpt
块中提出了另一个例外。解决此问题的最简单方法是添加嵌套
try-except
:您的问题的根源是您将列表传递给
If you look carefully at the stack trace you will see this snippet:
During handling of the above exception, another exception occurred
. This is telling you that the aboveKeyError
was caught, but another exception was raised in theexecpt
block.The simplest way to get around this would be to add a nested
try-except
:The root of your issue here is that you are passing a list to
os.path.join
expecting astr, bytes or os.PathLike object, not list
. My guess is you want to join theroot
value rather thandirs
. You can see something similar in an example for the docs foros.walk
:All in all your path joining code should look like this:
如果您需要收集错误位置列表,则只需要附加路径名
root
和文件名name
If you need to collect a list of error locations, you only need to append the path name
root
and filenamename