Python: Understanding Os. Listdir() Method

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?

2 Answers

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.

1

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

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett
Author

Chloe Bennett

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.