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

时光总嘲笑我的痴心妄想 提交于 2020-01-15 08:12:22

问题


If I have a folder structure as follows:

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

I want make files for each subfolder use subfolders' name. How can I do it in Python? Thanks. Expected result:

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
        .
        .
        .

Here is what I have tried:

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

回答1:


You can do that recursively:

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)

Note that this will only create textfiles with an xlsx ending and not actual excel files. Therefore you can install some library that is capable of creating excel files



来源:https://stackoverflow.com/questions/54254336/make-empty-file-for-each-subfolder-using-subfolders-name-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!