我想将仅img文件移动到另一个文件夹 如果文件夹不存在,我将使用原始名称+ ImageOnly
创建它例如。
D:\Test #contain some folder
D:\Test\aaa\img1.jpg
D:\Test\bbb\ccc\img2.jpg
import os
import shutil
def moveImage(srcdirs):
for roots, dirs, files in os.walk(srcdirs):
grand_father = srcdirs #D:\Test
not_need =('.zip','.js','.html','.log','.lst','.txt','.ini')
imgExt = ('.jpg','.png','.gif','.jpeg')
father = os.path.split(roots)[1]+'-ImageOnly'
for file in files:
if file.endswith(imgExt) and not file.endswith(not_need):
path = os.path.join(roots,file)
des= os.path.join(grand_father,father)
if not os.path.exists(des):
createFolder(father)
print("folder created")
shutil.move(path,des)
elif file.endswith(not_need): #remove unnecessary file
n1 = os.path.join(roots,file)
os.remove(n1)
def createFolder(directory):
dirs = ('./%s/'%directory)
try:
if not os.path.exists(dirs):
os.makedirs(dirs)
except OSError:
print ('Error: Creating directory. ' + dirs)
src = r'D:\Test'
moveImage(src)
我的代码给了我
img1.jpg
移至aaa-ImageOnly
但对于img2.jpg
,它移到了ccc-ImageOnly
我希望它移至bbb-ImageOnly
到第一个子文件夹名称(我叫对吗?),而不是最后一个子文件夹名称。
答案 0 :(得分:1)
您在这里:
import os
import shutil
FOLDER = r'D:\Test'
EXTENSIONS = ('.jpg', '.png', '.gif', '.jpeg')
def move_images(root):
levels = len(root.split(os.sep))
for path, dirs, files in os.walk(root):
for file in files:
if file.endswith(EXTENSIONS):
src_file = os.path.join(path, file)
dst_dir = os.path.join(root, '{}-ImageOnly'.format(path.split(os.sep)[levels]))
dst_file = os.path.join(dst_dir, file)
if not os.path.exists(dst_dir):
os.makedirs(dst_dir)
shutil.move(src_file, dst_file)
move_images(FOLDER)
它产生了我
D:\Test\aaa-ImageOnly\img1.jpg
D:\Test\bbb-ImageOnly\img2.jpg