使用 Python 中的子文件夹名称为每个子文件夹创建空文件

Make empty file for each subfolder using subfolders' name in Python

如果我的文件夹结构如下:

folder
        \ sub1\sub1_1
        \ sub1\sub1_2
        \ sub1\sub1_3
        .
        .
        .
        \ sub2\sub2_1
        \ sub2\sub2_2
        \ sub2\sub2_3
        .
        .
        .

我想让每个子文件夹的文件都使用子文件夹的名称。我怎样才能在 Python 中做到这一点?谢谢。 预期结果:

folder
        \ sub1\sub1_1\sub1_1.xlsx
        \ sub1\sub1_2\sub2_2.xlsx
        \ sub1\sub1_3\sub3_3.xlsx
        .
        .
        .
        \ sub2\sub2_1\sub2_1.xlsx
        \ sub2\sub2_2\sub2_2.xlsx
        \ sub2\sub2_3\sub2_3.xlsx
        .
        .
        .

这是我尝试过的:

import os
dir_name = "D:/folder"     
for root, dirs, files in os.walk(dir_name, topdown=False):
    for subfolder in dirs:
        print(subfolder)

你可以递归地做:

from os import listdir
from os.path import isfile, join

mypath = "add/your/path"

def write_files(path):
    folders = [f for f in listdir(path) if not isfile(join(path, f))]
    if len(folders) == 0:
        #Writing the actual File
        open(path+"/"+path.split("/")[-1]+".xlsx", "w+")
    else:
        for folder in folders:
            write_files(path+"/"+folder)

write_files(mypath)

请注意,这只会创建以 xlsx 结尾的文本文件,而不是实际的 excel 文件。 因此,您可以安装一些能够创建 excel 文件的库