【问题标题】:IndexError: list index out of range.how can i remove this error?IndexError: list index out of range. 如何消除此错误?
【发布时间】:2018-04-11 11:47:29
【问题描述】:
Traceback (most recent call last):
  File "/home/pi/codes/myprog.pyc", line 11, in <module>
    device_folder = glob.glob(base_dir+'28*')[0]
IndexError: list index out of range
>>> 

列表索引超出范围。如何消除此错误?

【问题讨论】:

标签: python


【解决方案1】:

glob.glob(base_dir+'28*') 将根据您的通配符返回一个目录/文件列表,如果没有找到任何目录/文件,它将返回一个像这样 [] 的空列表。因此,如果您尝试访问空列表的第 0 个元素,您将面临IndexError。只需检查您的路径是否正确。 我认为您缺少 os.sep

只需更改这一行:

device_folder = glob.glob(base_dir+'28*')[0]

到这里:

device_folder = glob.glob(base_dir+ os.sep +'28*')[0]

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2022-10-09
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2015-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多