Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用子文件夹为每个子文件夹创建空文件';Python中的名称_Python_Pandas_Operating System_Os.walk - Fatal编程技术网

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

使用子文件夹为每个子文件夹创建空文件';Python中的名称,python,pandas,operating-system,os.walk,Python,Pandas,Operating System,Os.walk,如果我有如下文件夹结构: 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\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文件的库

谢谢您的帮助!!我认为这可能有助于解决这个问题。你怎么认为?