I tried to figure out whether some images stored by the name in a text file exists in a specific image folder.
The text file looks like this (including 1k lines) :
4916849840_43930a0979_o.png
331595384_492146dbf3_k.png
13517809023_f49228b3ec_o.png
So I wrote the code like:
import os
txt_path = '/Users/owner/Desktop/360_dataset_3k/train/train_3k_1.txt'
images_path = '/Users/owner/Desktop/360_dataset_3k/360_512_3k_1/'
full_path = '/Users/owner/Desktop/360_dataset_3k/360_512_3k_1/27107804622_984dbb2181_o.png'
f = open(txt_path,"r")
lines = f.readlines()
for line in lines:
new_path = os.path.join(images_path, line)
print(new_path)
if os.path.exists(new_path):
print("True.\n")
else:
print("False.\n")
However, the outputs are endless False. BUT, when I replaced the new_path here
if os.path.exists(new_path):
print("True.\n")
with the variable full_path which is a print of new_path created by a line in lines.
if os.path.exists(full_path):
print("True.\n")
The outputs are True!!!
And after checking in a rather tedious way, it turns out they do exist in the image folder. Can somebody tell me what is going on please? THANKS SO MUCH.
CodePudding user response:
When you call the readlines() method for file object, each line has a newline character ('\n')
at the end. You need to strip line before joining the path.
Code:
f = open(txt_path,"r")
lines = f.readlines()
for line in lines:
line = line.strip() #Remove whitespace
new_path = os.path.join(images_path, line)
print(new_path)
if os.path.exists(new_path):
print("True.\n")
else:
print("False.\n")
Also close file object f.close()
when task is done.