【问题标题】:Make empty file for each subfolder using subfolders' name in Python在 Python 中使用子文件夹的名称为每个子文件夹创建空文件
【发布时间】:2019-06-12 17:45:21
【问题描述】:

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

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)

【问题讨论】:

    标签: python pandas operating-system os.walk


    【解决方案1】:

    你可以递归地做到这一点:

    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 文件的库

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-02
    • 1970-01-01
    • 2018-12-02
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多