我正在創建一個python函式,它將“n”個引數作為串列,并根據它們的位置創建檔案夾和嵌套檔案夾例如。
path = Path("Path to Directory")
root_folders = ['f1','f2','f3']
yr = ['2018', '2019']
mnth = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
“root_folders”應該是“path”中的主檔案夾 “yr”應該是每個“root_folders”的子檔案夾 “mnth”是每個“yr”的子檔案夾
我已經能夠使用以下代碼實作這一點:
def folder(root,*args):
for a in args[0]:
path = os.path.join(root, a)
if not os.path.exists(path):
os.mkdir(path)
for b in args[1] :
path2 = os.path.join(path, b)
if not os.path.exists(path2):
os.mkdir(path2)
for c in args[2] :
path3 = os.path.join(path2, c)
if not os.path.exists(path3):
os.mkdir(path3)
folder(path,root_folders,yr,mnth)
但這有一定的局限性,因為嵌套檔案夾增加了可擴展性將是一個問題。那么是否有任何解決方案可以使用遞回或任何其他方法來實作
uj5u.com熱心網友回復:
您可以使用遞回來創建檔案夾,在每次呼叫時向檔案夾創建函式傳遞一個運行路徑:
import os
def create_folders(root, *args):
if args:
for i in args[0]:
os.mkdir(p:=os.path.join(root, i))
create_folders(p, *args[1:])
root_folders = ['f1','f2','f3']
yr = ['2018', '2019']
mnth = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']
create_folders(os.getcwd(), root_folders, yr, mnth)
uj5u.com熱心網友回復:
不確定這是否是您想要的,但我為您準備了一個簡短的函式,它使用遞回從字典中創建檔案夾結構:
def folder(root, folderdict, subdir=""):
"""
The folderdict could look something like this:
folderdict = {folder1: None, folder2: None, folder3:{subfolder1: None, subfolder2: {subsubfolder1}}}
"""
# set up path progression for recursion
current_directory = os.path.join(root, subdir)
for foldername, subfolders in folderdict.items():
path = os.path.join(current_directory, foldername)
if not os.path.exists(path):
os.mkdir(path)
# check if newly created path should contain subfolders
# if so: start recursion
if subfolders is not None:
new_subdir = os.path.join(subdir, foldername)
folder(root, subfolders, new_subdir)
不過要小心。遞回通常不能很好地擴展。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/420345.html
標籤:
上一篇:Swift結構繼承默認值
