程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Office automation example] After creating a directory in excel, use python to generate multi-level folders in batches

編輯:Python

文章目錄

        • 一、需求
        • 二、處理方式
        • 三、代碼實現

一、需求

在excelCreate a directory first,然後使用pythonGenerate multi-level folders in batches.如圖:

二、處理方式

1、先在excel 文件中,Create the relevant file hierarchy;
2、通過pandas讀取excel文件,並做相應處理;
3、通過osThe module creates multiple layers of folders.
注:
1、python版本 3.8

三、代碼實現

import os
import pandas as pd
def merge_dir(x,fill_dir):
''' Delete folders under empty paths '''
try:
n = str(x).split('/').index(fill_dir) # Locate the location of the empty folder
x = '/'.join(str(x).split('/')[0:n]) # Delete the path of the empty folder
except Exception as e:
print(e)
return str(x)
df=pd.read_excel('文件夾目錄.xlsx')
#There are null values ​​in the column,Direct merging does not work,One processing is required.
df = df.fillna('空文件夾')
col = df.columns
n = len(df.columns)
df['all'] = df[col[1]].astype('str') # Write absolute path if needed,It can be modified for reference here"'d:/' + df[col[1]]"
for i in range(2,n):
df['all'] = df['all'] + '/' + df[col[i]].astype('str')
df['all'] = df['all'].apply(merge_dir,args=('空文件夾',)) #注意,這裡argsIf there is only one parameter in the parameter,A parenthesis is required
# 使用os模塊的makedirs創建多層文件夾
for f_dir in df['all'].to_list():
if not os.path.exists(f_dir):
os.makedirs(f_dir)
print(f'path completed:{
f_dir} Creation of all folders below')
else:
print('文件夾已存在')

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved