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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With