Issue
i'm trying to copy the images from folder to another which have the same name that exists in a file
dst="t"
path = 'train'
f = open("file_txt.txt",'r')
files = os.listdir(path)
for i in files :
if i.endswith('.jpg'):
j=i.rsplit('.', 1)[0]
#print(j)
lines = f.readlines()
for line in lines:
#print(line)
if line == j:
#print(line)
shutil.copy(path+'/'+line.strip(), dst)
j contains like
COCO_train2014_000000110431
COCO_train2014_000000110437
COCO_train2014_000000110439
line contains like
COCO_train2014_000000206463
COCO_train2014_000000206465
COCO_train2014_000000206467
but the new_folder is empty and I tried to print(line) that exists in if condition but got nothing while file_txt contains the name of the images and train is a folder contains the images itself
Solution
You have mess in code but I think your problem is that you try copy COCO_train2014_000000110431
without .jpg
but you have to copy COCO_train2014_000000110431.jpg
Other problem can be: you compare line
before you use .strip()
so it may has \n
at the end. So you compare if name<enter> == name
. If you run print(line)
then name may looks OK (because \n
is not visible) but if you would add some chars print(f">>>{line}<<<")
then maybe you would see that <<<
is in new line.
But I would do it in different way - without listdir()
but with os.path.exists()
import os
import shutil
src = 'train'
dst = 't'
os.makedirs(dst, exist_ok=True) # create destination folder if not exists
filenames = open("file_txt.txt").read().split('\n')
for name in filenames:
if name: # to skip empty lines
fullpath = os.path.join(src, name + '.jpg')
if os.path.exists(fullpath):
print('coping:', fullpath)
shutil.copy(fullpath, dst)
else:
print('SKIPING:', fullpath)
Answered By - furas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.