os.listdir(path)
,返回path目录下的文件夹和文件,但不包含子文件夹里的文件夹和文件
递归遍历所有文件
import os def recursive_listdir(path): files = os.listdir(path) for file in files: file_path = os.path.join(path, file) if os.path.isfile(file_path): print(file) elif os.path.isdir(file_path): recursive_listdir(file_path) recursive_listdir(r'./test')
os.walk(top, topdown=True, one rror=None, followlinks=False)
,生成目录树中的文件夹名和文件名。
显示所有子目录
import os paths = os.walk(r'./test') for path, dir_lst, file_lst in paths: for dir_name in dir_lst: print(os.path.join(path, dir_name))
显示目录下所有文件
import os paths = os.walk(r'./test') for path, dir_lst, file_lst in paths: for file_name in file_lst: print(os.path.join(path, file_name))
os.scandir 高效
遍历目录树
import os def traversal_files(path): for item in os.scandir(path): if item.is_dir(): dirs.append(item.path) elif item.is_file(): files.append(item.path) print('dirs:') print('\n'.join(dirs)) print() print('files:') print('\n'.join(files)) traversal_files(r'./test')
标签:files,遍历,python,lst,文件夹,file,print,path,os From: https://www.cnblogs.com/duoruaimi4/p/17616653.html