Patrice Gaofei
Patrice Gaofei

Reputation: 35

Python: Understanding os.listdir() Method

I am still a beginner with python and I would like to understand what the following code does.

files = [f for f in os.listdir('E:/figs/test') if os.path.isfile(f)]
imgs = []

#read input
for f in files:
    if 'jpg' in f and 'background' not in f:
        imgs.append(cv2.imread(f))

print(imgs)

As it can be seen, I have inserted a path to the folder containing the images. However, when I print the content, it is empty. Please, could anyone explain what could be the reason as well as the way for solving it?

Upvotes: 3

Views: 19996

Answers (2)

Ujjwal Dash
Ujjwal Dash

Reputation: 823

os.listdir() method in python is used to get the list of all files and directories in the specified directory. If we don’t specify any directory, then list of files and directories in the current working directory will be returned.

You have to use // instead of / in your folder path

Like this:

files = [f for f in os.listdir('E://figs//test') if os.path.isfile(f)]

Try this it may run

Upvotes: 0

ewokx
ewokx

Reputation: 2425

It's because os.path.isfile(f) is checking whether f is a file; but f is under E:/figs/text. What you should try is the following:


main_dir = "E:/figs/test"
files = [f for f in os.listdir(main_dir) if os.path.isfile(os.path.join(main_dir, f))]

As this will check the existence of the file f under E:/figs/text.

Upvotes: 4

Related Questions