Search code examples
pythonimageopencvlistdir

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?


Solution

  • 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.