使用Python中子文件夹的名称为每个子文件夹创建空文件 [英] Make empty file for each subfolder using subfolders' name in Python

查看:140
本文介绍了使用Python中子文件夹的名称为每个子文件夹创建空文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我希望每个子文件夹的文件都使用子文件夹的名称.如何在Python中完成?谢谢. 预期结果:

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

这是我尝试过的:

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

推荐答案

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

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)

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

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

这篇关于使用Python中子文件夹的名称为每个子文件夹创建空文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆