Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 735
Patrice Gaofei Avatar asked Oct 24 '25 04:10

Patrice Gaofei


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.

like image 119
ewokx Avatar answered Oct 26 '25 18:10

ewokx


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

like image 28
Ujjwal Dash Avatar answered Oct 26 '25 17:10

Ujjwal Dash