I am trying to move files from one folder to another folder within the same directory buy am coming across a problem.
This is what my code looks like thus far:
current_dir = os.path.dirname(os.path.realpath(__file__))
folders = get_all_folders(current_dir)
os.mkdir('FINAL') # Final output stored here
for folder in folders:
img_list = list(os.listdir(current_dir))
for img in img_list:
img_path = os.path.join(current_dir, img)
final_folder = os.path.join(current_dir, 'FINAL')
shutil.copyfile(img_path, final_folder)
The FINAL
folder is created as intended, however instad of copying the imgs over to that folder, a file called FINAL
is created in each directory I am looping through.
Any ideas on how I can solve this?
I think the mistake you are doing here is that you are trying to find the images in the current directory instead of folders in the current directory. So, when you call shutil.copyfile()
, you should ideally get a IsADirectoryError
as per the code provided by you. Anyways, I guess this should work:
current_dir = os.path.dirname(os.path.realpath(__file__))
# Get all folder names in current directory before making the "FINAL" folder.
folders = get_all_folders(current_dir)
os.mkdir('FINAL') # Final output stored here
for folder in folders:
folder_path = os.path.join(current_dir, folder)
img_list = list(os.listdir(folder_path))
for img in img_list:
img_path = os.path.join(folder_path, img)
final_folder = os.path.join(current_dir, 'FINAL')
shutil.copyfile(img_path, final_folder)
Also, you need to remove the FINAL folder each time you run this script. Better make such checks in the code itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.