有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
有没有办法在Python中返回当前目录中所有子目录的列表?
我知道您可以对文件执行此操作,但我需要获得目录列表。
当前回答
有很多很好的答案,但如果你来这里寻找一个简单的方法来获得所有文件或文件夹的列表。你可以利用linux和mac上提供的find操作系统,它比os.walk快得多
import os
all_files_list = os.popen("find path/to/my_base_folder -type f").read().splitlines()
all_sub_directories_list = os.popen("find path/to/my_base_folder -type d").read().splitlines()
OR
import os
def get_files(path):
all_files_list = os.popen(f"find {path} -type f").read().splitlines()
return all_files_list
def get_sub_folders(path):
all_sub_directories_list = os.popen(f"find {path} -type d").read().splitlines()
return all_sub_directories_list
其他回答
这是简单的递归解
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))
你可以用glob。glob
from glob import glob
glob("/path/to/directory/*/", recursive = True)
不要忘记*后面的/。
通过从这里加入多个解决方案,这是我最终使用的:
import os
import glob
def list_dirs(path):
return [os.path.basename(x) for x in filter(
os.path.isdir, glob.glob(os.path.join(path, '*')))]
我更喜欢使用滤镜(https://docs.python.org/2/library/functions.html#filter),但这只是个人喜好问题。
d='.'
filter(lambda x: os.path.isdir(os.path.join(d, x)), os.listdir(d))
这应该可以工作,因为它还创建了一个目录树;
import os
import pathlib
def tree(directory):
print(f'+ {directory}')
print("There are " + str(len(os.listdir(os.getcwd()))) + \
" folders in this directory;")
for path in sorted(directory.glob('*')):
depth = len(path.relative_to(directory).parts)
spacer = ' ' * depth
print(f'{spacer}+ {path.name}')
这应该列出使用pathlib库的文件夹中的所有目录。path.relative_to(目录)。Parts获取相对于当前工作目录的元素。