我如何列出目录中的文件夹

新手上路,请多包涵

这是我的代码:

 import os

def get_file():
    files = os.listdir('F:/Python/PAMC')
    print(files)

    for file in files:
        print(file)

get_file()

我如何只列出 python 目录中的文件夹?

原文由 MOHS3N 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 404
1 个回答

在 Python 3.6 中尝试并测试了以下代码

import os

filenames= os.listdir (".") # get all files' and folders' names in the current directory

result = []
for filename in filenames: # loop through all the files and folders
    if os.path.isdir(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a folder or not
        result.append(filename)

result.sort()
print(result)

#To save Foldes names to a file.
f= open('list.txt','w')
for index,filename in enumerate(result):
    f.write("%s. %s \n"%(index,filename))

f.close()

替代方式:

 import os
for root, dirs, files in os.walk(r'F:/Python/PAMC'):
    print(root)
    print(dirs)
    print(files)

替代方式

import os
next(os.walk('F:/Python/PAMC'))[1]

原文由 Ramineni Ravi Teja 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题