1

As part of my project, my tool asks the user to input a folder, all the files contained in the folder are stored in a list and used later. I need to make it so that the list will only contain files which are of the ".jpg" or ".tiff" file format, therefore removing any files which are not of that file format. I cannot seem to figure out how to do this. How do I go about removing any other file formats from the list? I will post below one example of what I have already tried.

files = os.listdir(file_dir)

for file in files:
    if not files.endswith(".jpg", ".tiff"):
        files = files.remove(file)
Aaron_ab
  • 3,450
  • 3
  • 28
  • 42
Jonathan
  • 15
  • 3
  • Also never change a container while iterating over it. For example, iterate over a copy like `original_list[:]` while you change the `original_list`. – progmatico Dec 18 '18 at 14:17
  • 1
    you probably mean `if not file.ends...`, not `files`; `files` is a list and as such, has no `endswith` method. – Ma0 Dec 18 '18 at 14:18

3 Answers3

5

Use

files = [f for f in os.listdir(file_dir) if (f.endswith(".jpg") or f.endswith(".tiff"))]
grapes
  • 8,185
  • 1
  • 19
  • 31
2

You can use glob module, it will list all the matched path name.

import glob

files = []

for f in glob.glob("*.jpg"):
    files.append(f)
for f in glob.glob("*.tiff"):
    files.append(f)
Lester_wu
  • 151
  • 5
0

On the line starting with 'if' you are checking files, not file. And 'endswith' needs a tuple. This should work:

 files = os.listdir(file_dir)

 for file in files:
     if not file.endswith((".jpg", ".tiff")):
        files.remove(file)
Zoe
  • 1,402
  • 1
  • 12
  • 21