[英]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?此当前代码会将所有
pngs
从源目录移动到图像目录,我如何才能使其还包括嵌套在源目录内另一个子目录中的pngs
? for example C:\\Users\\Andre\\Downloads\\pictures
例如
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.您可以简单地更改
source_dir
以包含要从中移动pngs
的子目录,然后再次运行循环。
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.