lemi
lemi

Reputation: 111

Python - How to find all same types of files in a folder and make a list out of it?

I've tried this code to find all the 'jpg' files in a folder and make a list out of it. But the result shows something like as below.

['0', '0', '0', '1', '0', '8', '.', 'j', 'p', 'g']
['0', '0', '0', '1', '0', '8', '.', 'j', 'p', 'g', '0', '0', '0', '1', '1', '4', '.', 'j', 'p', 'g']

It returns all the characters of the names of the files to list not the names of the files in a whole. How do you solve this problem? Thanks in advance.

import os 

def find_names(outpath):
    root_path_list= [file for file in os.listdir(outpath)]
    jpg_file_list = []
    for idx, file in enumerate(root_path_list) :
        if file.endswith('.jpg'):
            jpg_file_list += file             
            print(jpg_file_list)

Upvotes: 1

Views: 775

Answers (5)

Glenn Mackintosh
Glenn Mackintosh

Reputation: 2790

Others have commented on ways of creating the list of file extension matches. They do not directly clarify what I believe is the other part of the answer to your question, why the individual letters are ending up in your jpg_file_list rather than the filename string.

One of the things that is touched on but not explicitly stated by the answers here is that a string (such as the filenames) is a type of collection.

That is useful so that you can iterate over the characters in the string, index into it and take slices of it. It can be a nuisance though in some cases when you're thinking of it as an item and the code treats it like a list.

In your code the filename string is being treated like a list not a single item and the characters are added into the list individually rather than the filename as a single entry.

As others have already said, to change your code to deal with the fact that strings are collections, you would need to change:

jpg_file_list += file 

to

jpg_file_list += [file]

or

jpg_file_list.append(file)

Upvotes: 0

Jim Chen
Jim Chen

Reputation: 3729

I prefer to use glob library :

One line can solve your problem :

import glob, os
glob.glob(os.path.join(outpath,"*.jpg"))

For your code , if you want to append element into a list, you must += a list.

jpg_file_list += [file] 

or use append

jpg_file_list.append(file)

Upvotes: 1

user2585435
user2585435

Reputation: 131

import os
import glob

files = [os.path.basename(i) for i in glob.glob('*.jpg')]

Note the extension is case sensitive, if you have files with a JPG extension you will need do some further work.

Upvotes: 1

Gabio
Gabio

Reputation: 9484

You can use list comprehension:

import os 

def find_names(outpath):
    return [file for file in os.listdir(outpath) if file.lower().endswith(".jpg")]

Upvotes: 1

wstk
wstk

Reputation: 1270

Append the entry to the list

jpg_file_list.append(file)

Upvotes: 0

Related Questions