一、需求
根据项目需求,需要创建一系列文件夹,用于对文件进行分类存放。
二、思路
1、在excel文件中,按照如下图示分别设置文件夹层级;
2、使用pandas读取excel文件的内容;
3、组合文件夹的路径;
4、处理异常的数据;
5、创建文件夹,并删除不需要的文件夹。
生成的例子:
三、整体代码
import glob
import shutil
df = pd.read_excel('文件夹目录.xlsx')
col = df.columns.tolist()
df = df.fillna('空文件夹')
#创建文件夹路径
for n in range(1,len(col)):
df[col[n]] = df[[col[n-1], col[n]]].apply(lambda x:'//'.join(x), axis=1)
#创建文件夹
for m in range(len(col)):
for file in df[col[m]].tolist():
if not os.path.exists(file):
os.mkdir(file)
for file in glob.glob('**/*',recursive=True):
try: # 这里使用try 的方法,是因为空文件夹被移除后,还会被读取到,会报错。
if '空文件夹' in file:
shutil.rmtree(file)
except:
pass