0

Trying to debug a Python script, and keep being this error message:

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

Since the file names have no integers... this doesn't seem to make any sense. Any suggestions?

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
10
  • 1
    Is this whole of your code?
    – Mazdak
    Commented Jul 14, 2015 at 13:55
  • 4
    str.endswith expects a tuple instead of multiple arguments. Commented Jul 14, 2015 at 13:56
  • 1
    Hello and welcome to StackOverflow. Please take some time to read the help page, especially the sections named "What topics can I ask about here?" and "What types of questions should I avoid asking?". And more importantly, please read the Stack Overflow question checklist. You might also want to learn about Minimal, Complete, and Verifiable Examples. Commented Jul 14, 2015 at 13:57
  • StackOverflow isn't really about discussion threads, it's clear questions and clear answers. The discussion is usually to clarify the question if the asker hasn't been clear enough. Commented Jul 14, 2015 at 14:01
  • 2
    @WombatBob no, you didn't - the traceback is missing the actual line that caused the error, which would have made it much easier for people to figure out what the problem actually was. Also the code is not as short as possible - my answer demonstrates that a single line is sufficient to replicate the error, which you should have attempted to cut your code down to.
    – jonrsharpe
    Commented Jul 14, 2015 at 16:17

1 Answer 1

9

You are misusing str.endswith. The second and third* parameters are start and end, which are used to index into the string, not additional strings to check for. By default these are both None, hence checking the whole string:

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

This explains the seemingly-confusing error message; Python is trying to check filename['.jpg':None].endswith('.jpeg'), which clearly doesn't make any sense. Instead, to check for multiple strings, pass a single tuple as the first parameter:

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

Demo:

>>> '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

* (or third and fourth, as instance.method(arg) can be written Class.method(instance, arg))

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.