另一个"切片索引必须是整数或无或具有__index__方法"线程



尝试调试Python脚本,并保持此错误信息:

 Traceback (most recent call last):
    File "<input>", line 3, in <module>
TypeError: slice indices must be integers or None or have an __index__ method

由于文件名没有整数…这似乎没有任何意义。有什么建议吗?

import os
inputFolder = "d:\full"
outputFolder = "d:\clean"
for path, dir, file in os.walk(inputFolder):
    for filename in file:
        if filename.endswith(".jpeg", ".jpg"):
            inputPath = inputFolder + os.sep + filename
            print inputPath

您正在滥用str.endswith。第二个和第三个*参数是startend,它们用于索引到字符串,而不是其他要检查的字符串。默认情况下,这两个都是None,因此检查整个字符串:

>>> 'foo'[None:None]
'foo'

这解释了看起来令人困惑的错误消息;Python试图检查filename['.jpg':None].endswith('.jpeg'),这显然没有任何意义。相反,要检查多个字符串,将单个元组传递给作为第一个参数:

if filename.endswith((".jpeg", ".jpg")):
                   # ^ note extra parentheses
演示:

>>> 'test.jpg'.endswith('.jpg', '.jpeg')
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    'test.jpg'.endswith('.jpg', '.jpeg')
TypeError: slice indices must be integers or None or have an __index__ method
>>> 'test.jpg'.endswith(('.jpg', '.jpeg'))
True

* (或第三和第四,因为instance.method(arg)可以写成Class.method(instance, arg))

最新更新