1

I'm trying to find files in a directory that have a certain extension. My code looks like this.

   extensions = ('.txt')
   for subdir, dirs, files in os.walk(rootdir):
        for file in files:
            ext = os.path.splitext(file)[-1].lower()
            print(ext)
            if ext in extensions:
                print('.txt found')

The code almost always works fine. However, if the file does not have an extension it somehow returns .txt found.

John827
  • 11
  • 1
  • 1
    What do you think `extensions` is? It's not a tuple, it's a string. To create a single-element tuple: `extensions = ('.txt',)` – dspencer Apr 04 '20 at 04:46
  • Thank you. Works fine now I feel so dumb. – John827 Apr 04 '20 at 05:11
  • Does this answer your question? [How to create a tuple with only one element](https://stackoverflow.com/questions/12876177/how-to-create-a-tuple-with-only-one-element) – Gino Mempin Apr 04 '20 at 05:32

1 Answers1

1

extensions = ('.txt') isn't doing what you think it's doing. Removing the parentheses would have the same result. As it's just creating a str with the value '.txt' and so when no extension is found it's checking:

'' in '.txt' which returns True

you want: extensions = ['.txt']

which will make a list instead of a str.

Kourpa
  • 86
  • 2