如何读取文件夹名称并将结果输出到字符串

How to read a folder name and output result to a string

我有一些读取目录名和文件名的代码

import os

#define the folder you want to use
myfolder = path/to/directory

#read directories
for dirs in os.walk(myfolder):        
    for dir in dirs:
        print("Directory name = %s" %dir

假设在 -myfolder- 中,我有一个名为 -mysecondfolder-

的目录

是否可以将文件名输出为字符串

类似于

for dirs in os.walk(myfolder):
    for dir in dirs:
        targetfolder="%dir"

你可以这样试试:

for root, dirs, files in os.walk(myfolder, topdown=False):
    targetfolder = dirs