问题
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