[英]How to crop all pictures in a folder and save it to another folder by python
[英]How to move the pictures in all subfolders to another new same folder in Python?
我打算將火車文件train/LUAD
下所有子文件夾(如圖所示)中的圖片移動到另一個新文件夾train_new/LUAD
中。 每個子文件夾中都有.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)
但它不起作用。 除了我的新文件夾train_new/LUAD
中的其他子文件夾外,我只從最后一個子文件夾中獲取圖像...
只是為了澄清一下,您想將圖像從嵌套文件結構移動(而不是復制)到新文件夾而不嵌套?
請注意,如果多個圖像共享相同的名稱,這可能會覆蓋圖像!
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))
如果您不確定,可以先使用副本 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.