简体   繁体   中英

How do I move files within a subfolder in a directory to another directory in python?

import os
import shutil
source_dir = r'C:\\Users\\Andre\\Downloads'
image_dir = r'C:\\Users\\Andre\\Downloads\\images'

file_names = os.listdir(source_dir)
    
for file_name in file_names:
    if '.png' in file_name:
        shutil.move(os.path.join(source_dir, file_name), image_dir)

This current code will move all pngs from source dir to image dir, how can I make it so it also includes pngs nested in another subdirectory inside the source dir? for example C:\\Users\\Andre\\Downloads\\pictures

You can break the moving functionality into a function, then call that function on each directory.

def move_pngs(src, dst):
    for file_name in os.listdir(src):
        if file_name.endswith('.png'):
            shutil.move(os.path.join(src, file_name), dst)

move_pngs(source_dir, image_dir)
move_pngs(os.path.join(source_dir, 'pictures'), image_dir)

... Or maybe go full recursive.

def move_pngs(src, dst):
    for file_name in os.listdir(src):
        fullname = os.path.join(src, file_name)
        if os.path.isdir(fullname) and fullname != dst:
            move_pngs(fullname, dst)
        elif file_name.endswith('.png'):
            shutil.move(fullname), dst)

This will visit all subdirectories recursively, and move all files into one flat directory, meaning if there are files with the same names anywhere, generally the one from a deeper subdirectory will win, and the others will be overwritten.

You can simply just change the source_dir to also include the subdirectory which you want to move the pngs from and run then the loop again.
In this case:

subdirectory = '\pictures'
source_dir += subdirectory 

file_names = os.listdir(source_dir)    
for file_name in file_names:
    if '.png' in file_name:
        shutil.move(os.path.join(source_dir, file_name), image_dir)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM