[英]How to move the pictures in all subfolders to another new same folder in Python?
I plan to move the pictures in all subfolders (as shown in the picture) under the train file train/LUAD
to another new folder train_new/LUAD
.我打算将火车文件train/LUAD
下所有子文件夹(如图所示)中的图片移动到另一个新文件夹train_new/LUAD
中。 There are .jpg
images in each subfolder such as the first one in the picture TCGA-05-4249-01Z-00-DX1.9fce0297-cc19-4c04-872c-4466ee4024db
.每个子文件夹中都有.jpg
图片,例如图片TCGA-05-4249-01Z-00-DX1.9fce0297-cc19-4c04-872c-4466ee4024db
中的第一个。
import os
import shutil
count = 0
def moveFiles(path, disdir):
dirlist = os.listdir(path)
for i in dirlist:
child = os.path.join('%s/%s' % (path, i))
if os.path.isfile(child):
imagename, jpg = os.path.splitext(i)
shutil.copy(child, os.path.join(disdir, imagename + ".jpg"))
continue
moveFiles(child, disdir)
if __name__ == '__main__':
rootimage = '/content/drive/MyDrive/stat841_final_data/train/LUAD'
disdir = '/content/drive/MyDrive/stat841_final_data/train_new/LUAD'
moveFiles(rootimage, disdir)
But it does not work.但它不起作用。 I only got image from the last subfolder except for other subfolders in my new folder train_new/LUAD
...除了我的新文件夹train_new/LUAD
中的其他子文件夹外,我只从最后一个子文件夹中获取图像...
Just to clarify, you want to move (not copy) images from a nested file structure to a new folder, without nesting?只是为了澄清一下,您想将图像从嵌套文件结构移动(而不是复制)到新文件夹而不嵌套?
Be aware that this could overwrite images, if multiple images share the same name!请注意,如果多个图像共享相同的名称,这可能会覆盖图像!
import pathlib
def move_files(source_folder:pathlib.Path, target_folder:pathlib.Path):
target_folder.mkdir(parents=True, exist_ok=True)
for image_file in source_folder.rglob("*.jpg"): # recursively find image paths
image_file.rename(target_folder.joinpath(image_file.name))
If you are unsure maybe use the copy function first, so you won't lose your original data:如果您不确定,可以先使用副本 function,这样您就不会丢失原始数据:
import pathlib
import shutil
def move_files(source_folder:pathlib.Path, target_folder:pathlib.Path):
target_folder.mkdir(parents=True, exist_ok=True)
for image_file in source_folder.rglob("*.jpg"): # recursively find image paths
shutil.copy(image_file, target_folder.joinpath(image_file.name))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.