python try /除了似乎与KeyError配合使用

发布于 2025-02-02 22:05:15 字数 2139 浏览 4 评论 0原文

尽管我已经使用了尝试/除了数百次以外的条款,但我以前从未见过这样的行为,现在我感到困惑。我可以知道我想念什么吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心的憧憬 2025-02-09 22:05:15

如果您仔细查看堆栈跟踪,您将看到此片段:在处理上述异常时,发生了另一个例外。这告诉您上述keyError被捕获了,但是在execpt块中提出了另一个例外。

解决此问题的最简单方法是添加嵌套try-except

        try:
            to_print = season_ep[name.split('-')[-1][:-4]]
            print(to_print)
        except KeyError:
            try:
                errors.append(os.path.join(dirs, name))
            except TypeError:
                # handle this error somehow
                pass

您的问题的根源是您将列表传递给

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

                errors.append(os.path.join(root, name))

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 above KeyError was caught, but another exception was raised in the execpt block.

The simplest way to get around this would be to add a nested try-except:

        try:
            to_print = season_ep[name.split('-')[-1][:-4]]
            print(to_print)
        except KeyError:
            try:
                errors.append(os.path.join(dirs, name))
            except TypeError:
                # handle this error somehow
                pass

The root of your issue here is that you are passing a list to os.path.join expecting a str, bytes or os.PathLike object, not list. My guess is you want to join the root value rather than dirs. You can see something similar in an example for the docs for os.walk:

# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

All in all your path joining code should look like this:

                errors.append(os.path.join(root, name))
厌味 2025-02-09 22:05:15

如果您需要收集错误位置列表,则只需要附加路径名root和文件名name

    try:
        to_print = season_ep[name.split('-')[-1][:-4]]
        print(to_print)
    except KeyError:
        #errors.append(os.path.join(dirs, name))
        errors.append(os.path.join(root, name))

If you need to collect a list of error locations, you only need to append the path name root and filename name

    try:
        to_print = season_ep[name.split('-')[-1][:-4]]
        print(to_print)
    except KeyError:
        #errors.append(os.path.join(dirs, name))
        errors.append(os.path.join(root, name))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文