有没有办法在Python中返回当前目录中所有子目录的列表?

我知道您可以对文件执行此操作,但我需要获得目录列表。


当前回答

使用python-os-walk实现。(http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/)

import os

print("root prints out directories only from what you specified")
print("dirs prints out sub-directories from root")
print("files prints out all files from root and directories")
print("*" * 20)

for root, dirs, files in os.walk("/var/log"):
    print(root)
    print(dirs)
    print(files)

其他回答

import os
path = "test/"
files = [x[0] + "/" + y for x in os.walk(path) if len(x[-1]) > 0 for y in x[-1]]

使用python-os-walk实现。(http://www.pythonforbeginners.com/code-snippets-source-code/python-os-walk/)

import os

print("root prints out directories only from what you specified")
print("dirs prints out sub-directories from root")
print("files prints out all files from root and directories")
print("*" * 20)

for root, dirs, files in os.walk("/var/log"):
    print(root)
    print(dirs)
    print(files)

我们可以使用os.walk()来获取所有文件夹的列表

import os

path = os.getcwd()

pathObject = os.walk(path)

这个pathObject是一个对象,我们可以通过

arr = [x for x in pathObject]

arr is of type [('current directory', [array of folder in current directory], [files in current directory]),('subdirectory', [array of folder in subdirectory], [files in subdirectory]) ....]

我们可以通过遍历arr并打印中间的数组来获得所有子目录的列表

for i in arr:
   for j in i[1]:
      print(j)

这将打印所有子目录。

获取所有文件:

for i in arr:
   for j in i[2]:
      print(i[0] + "/" + j)

这是简单的递归解

import os
def fn(dir=r"C:\Users\aryan\Downloads\opendatakit"):  # 1.Get file names from directory
    file_list = os.listdir(dir)
    res = []
    # print(file_list)
    for file in file_list:
        if os.path.isfile(os.path.join(dir, file)):
                res.append(file)
        else:
            result = fn(os.path.join(dir, file))
            if result:
                res.extend(fn(os.path.join(dir, file)))
    return res


res = fn()
print(res)
print(len(res))

这个答案似乎并不存在。

directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]