有没有办法在Python中返回当前目录中所有子目录的列表?
我知道可以获取文件列表,但我需要获取目录列表。
有没有办法在Python中返回当前目录中所有子目录的列表?
我知道可以获取文件列表,但我需要获取目录列表。
使用os walk功能
sub_folders = []
for dir, sub_dirs, files in os.walk(test_folder):
sub_folders.extend(sub_dirs)
这个答案似乎还不存在。
directories = [ x for x in os.listdir('.') if os.path.isdir(x) ]
对于像我这样只需要获取目录中立即子文件夹名称的人,在Windows上可以使用以下方法。
import os
for f in os.scandir(mypath):
print(f.name)
import pathlib
def list_dir(dir):
path = pathlib.Path(dir)
dir = []
try:
for item in path.iterdir():
if item.is_dir():
dir.append(item)
dir = dir + list_dir(item)
return dir
except FileNotFoundError:
print('Invalid directory')
pathlib
是从版本3.4开始新增的。
返回给定文件路径下所有子目录的列表的函数。将搜索整个文件树。
import os
def get_sub_directory_paths(start_directory, sub_directories):
"""
This method iterates through all subdirectory paths of a given
directory to collect all directory paths.
:param start_directory: The starting directory path.
:param sub_directories: A List that all subdirectory paths will be
stored to.
:return: A List of all sub-directory paths.
"""
for item in os.listdir(start_directory):
full_path = os.path.join(start_directory, item)
if os.path.isdir(full_path):
sub_directories.append(full_path)
# Recursive call to search through all subdirectories.
get_sub_directory_paths(full_path, sub_directories)
return sub_directories
directory
,并递归遍历它的所有子目录,并打印
出它发现的所有文件名
。非常实用。import os
def printDirectoryFiles(directory):
for filename in os.listdir(directory):
full_path=os.path.join(directory, filename)
if not os.path.isdir(full_path):
print( full_path + "\n")
def checkFolders(directory):
dir_list = next(os.walk(directory))[1]
#print(dir_list)
for dir in dir_list:
print(dir)
checkFolders(directory +"/"+ dir)
printDirectoryFiles(directory)
main_dir="C:/Users/S0082448/Desktop/carpeta1"
checkFolders(main_dir)
input("Press enter to exit ;")
使用过滤器函数os.path.isdir
,对os.listdir()
进行过滤。类似这样的代码:filter(os.path.isdir,[os.path.join(os.path.abspath('路径'),p) for p in os.listdir('路径/')])
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]) ....]
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
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()
或者
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
import glob
def list_dirs(path):
return [os.path.basename(x) for x in filter(
os.path.isdir, glob.glob(os.path.join(path, '*')))]
[f for f in data_path.iterdir() if f.is_dir()]
。这将返回文件夹名称作为字符串,还会自动排除.
和..
,非常感谢。另外,glob.glob解决方案也很有价值:glob.glob("/path/to/directory/*/")
。 - Charlie Parker