import os import shutil genpath = "F:/项目/图片" datanames = os.listdir(genpath) # 获取目录下的所有文件 for i in datanames: # 遍历 flag = True name = i i = i.split(".")[0] # 获取文件名,例如文件名为"qwe_asd_zxc.j
import shutil
genpath = "F:/项目/图片"
datanames = os.listdir(genpath) # 获取目录下的所有文件
for i in datanames: # 遍历
flag = True
name = i
i = i.split(".")[0] # 获取文件名,例如文件名为"qwe_asd_zxc.jpg",此时i="qwe_asd_zxc"
i = i.split("_")[1] +"_" + i.split("_")[2] # 将文件名按照“_"分开,例如文件名为"qwe_asd_zxc",此时i="asd_zxc"
for dirpath, dirnames, filenames in os.walk(genpath): # 获取文件夹目录下的所有文件夹,dirnames就是获取到的文件夹
for filepath in dirnames:
if filepath == i: # 判断目录是否存在,若存在,直接将文件移入
old_path = genpath + '/' + name
new_path = genpath + '/' + i
file = name
src = os.path.join(old_path, file)
dst = os.path.join(new_path, file)
print(new_path)
shutil.move(old_path, new_path) # 将文件移入文件夹
flag = False # 将标记置为False,就不执行下面的语句了
if flag: # 若不存在,
os.makedirs(genpath+'/'+i) # 新建文件夹
old_path = genpath + '/' + name
new_path = genpath+'/'+i
file = name
src = os.path.join(old_path, file)
dst = os.path.join(new_path, file)
print(new_path)
shutil.move(old_path, new_path)