Search For Certain Files With Specific Condition And Copy All Files In Another Folder Python
I have data like this; id record_id Type 2001 1 A 2002 2 B 2002 3 B 2004 4 A 2004 5 A 2005 6
Solution 1:
file.csv:
id,record_id,Type2001,1,A2002,2,B2002,3,B2004,4,A2004,5,A2005,6,C2006,7,A2007,8,A
Do:
import os
from shutil import copyfile
import pandas as pd
rootdir = 'E:Files/user_data'
output_path = 'E:/Files/Test_Folder/'defpath_source_img(_id, record_id):
global rootdir
return os.path.join(rootdir, str(_id), '{}.jpg'.format(record_id))
defpath_dest_img(_type, _id, record_id):
global output_path
return os.path.join(output_path, _type,
'{}_{}_{}.jpg'.format(_type, _id, record_id))
df = pd.read_csv('file.csv')
ifnot os.path.exists(output_path):
os.makedirs(os.path.dirname(output_path))
for _typein df['Type'].unique():
imgs = df[df['Type'] == _type]
for index, img in imgs.iterrows():
from_img = path_source_img(img['id'], img['record_id'])
to_img = path_dest_img(_type, img['id'], img['record_id'])
print(from_img, '->', to_img)
ifnot os.path.exists(output_path):
os.makedirs(os.path.dirname(to_img))
copyfile(from_img, to_img)
Solution 2:
I tried something similar and carried out few modification based on my requirement.
import os
from shutil import copyfile
import pandas as pd
rootdir = 'Mention the root directory here'
output_path = 'Mention the output path'
df = pd.read_csv('mention the path to the csv file')
If the name of the image is in number format then use this
df['id'] = df['id'].astype('str')
defpath_source_img(_id, record_id):
global rootdir
return os.path.join(rootdir, str(_id), '{}.jpg'.format(record_id))
defpath_dest_img(_type, _id, record_id):
global output_path
return os.path.join(output_path, _type,
'{}.jpg'.format(record_id))
function def ensure_dir will create folder if required, if folder in the destination path is not available
def ensure_dir(file_path):
directory = os.path.dirname(file_path)
if not os.path.exists(directory):
os.makedirs(directory)
for _type in df['Type'].unique():
imgs = df[df['Type'] == _type]
for index, img in imgs.iterrows():
from_img = path_source_img(img['id'], img['record_id'])
to_img = path_dest_img(_type, img['id'], img['record_id'])
from_img = '/'.join(from_img.split('\\'))
to_img = '/'.join(to_img.split('\\'))
print(from_img, '->', to_img)
ensure_dir(to_img)
copyfile(from_img, to_img)
Post a Comment for "Search For Certain Files With Specific Condition And Copy All Files In Another Folder Python"