源数据是这样的
想要的效果是这样的
注意:你文件后缀名是什么你就在 suffix_data 这个数组中添加一下
2022年4月13号,将 suffix 由
.jpg
改为元组('.jpg', '.png', '.JPG', '.psd', '.afphoto')
(这样只有一个图片也能新建文件夹)
# -*- coding: UTF-8 -*-
import os
import time
import shutil
root_path = input('请输入要生成文件的地址:')
root_path = root_path.strip().rstrip('\\')
def append_data(root_path):
data = []
try:
for filename in os.listdir(root_path):
if(filename.endswith(suffix)):
filename = filename.split('.')[0]
data.append(filename)
makedirs(root_path, data)
except FileNotFoundError:
print('地址输入错误,请检查地址'.center(20, '-'))
time.sleep(1.2)
def makedirs(root_path, data):
for folder in data:
folder_path = root_path + '\\' + folder
if not os.path.exists(folder_path):
os.makedirs(folder_path)
for suffix_append in suffix_data:
filename_all = root_path + '\\' + folder + suffix_append
if(os.path.isfile(filename_all)):
shutil.move(filename_all, folder_path)
else:
for suffix_append in suffix_data:
filename_all = root_path + '\\' + folder + suffix_append
if(os.path.isfile(filename_all)):
shutil.move(filename_all, folder_path)
print('移动完毕'.center(20, '-'))
time.sleep(1.2)
if __name__ == "__main__":
suffix_data = ['.jpg', '.png', '.JPG', '.psd', '.afphoto']
suffix = tuple(suffix_data)
append_data(root_path)
如果只是想让图片移动到文件夹,可以使用如下代码:
# -*- coding: UTF-8 -*-
import os
import shutil
root_path = input('请输入要生成文件的地址:')
root_path = root_path.strip().rstrip('\\')
def makedirs():
for dirpath, dirnames, files in os.walk(root_path):
for file in files:
folder_path = os.path.join(root_path, file.split('.')[0])
file_path = os.path.join(dirpath, file)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
shutil.move(file_path, folder_path)
print('移动完毕'.center(20,'-'))
if __name__ == "__main__":
makedirs()