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)
from pathlib import WindowsPath
def SubDirPath (d):return [f for f in d.iterdir() if f.is_dir()]
subdirs = SubDirPath(WindowsPath(r'\\file01.acme.local\home$'))print(subdirs)
import ostest_directory = <your_directory>for child in os.listdir(test_directory):test_path = os.path.join(test_directory, child)if os.path.isdir(test_path):print test_path# Do stuff to the directory "test_path"
from pathlib import Pathpaths = list(Path('myhomefolder', 'folder').glob('**/*.txt'))
# all sorts of operationsfile = paths[0]file.namefile.stemfile.parentfile.suffix
print("\nWe are listing out only the directories in current directory -")directories_in_curdir = list(filter(os.path.isdir, os.listdir(os.curdir)))print(directories_in_curdir)
仅列出当前目录中的文件
files = list(filter(os.path.isfile, os.listdir(os.curdir)))print("\nThe following are the list of all files in the current directory -")print(files)
def fast_scandir(dirname):subfolders= [f.path for f in os.scandir(dirname) if f.is_dir()]for dirname in list(subfolders):subfolders.extend(fast_scandir(dirname))return subfolders
os.scandir took 1 ms. Found dirs: 439os.walk took 463 ms. Found dirs: 441 -> it found the nested one + base folder.glob.glob took 20 ms. Found dirs: 439pathlib.iterdir took 18 ms. Found dirs: 439os.listdir took 18 ms. Found dirs: 439
使用W7x64、Python 3.8.1进行测试。
# -*- coding: utf-8 -*-# Python 3
import timeimport osfrom glob import globfrom pathlib import Path
directory = r"<insert_folder>"RUNS = 1
def run_os_walk():a = time.time_ns()for i in range(RUNS):fu = [x[0] for x in os.walk(directory)]print(f"os.walk\t\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")
def run_glob():a = time.time_ns()for i in range(RUNS):fu = glob(directory + "/*/")print(f"glob.glob\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")
def run_pathlib_iterdir():a = time.time_ns()for i in range(RUNS):dirname = Path(directory)fu = [f for f in dirname.iterdir() if f.is_dir()]print(f"pathlib.iterdir\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")
def run_os_listdir():a = time.time_ns()for i in range(RUNS):dirname = Path(directory)fu = [os.path.join(directory, o) for o in os.listdir(directory) if os.path.isdir(os.path.join(directory, o))]print(f"os.listdir\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms. Found dirs: {len(fu)}")
def run_os_scandir():a = time.time_ns()for i in range(RUNS):fu = [f.path for f in os.scandir(directory) if f.is_dir()]print(f"os.scandir\t\ttook {(time.time_ns() - a) / 1000 / 1000 / RUNS:.0f} ms.\tFound dirs: {len(fu)}")
if __name__ == '__main__':run_os_scandir()run_os_walk()run_glob()run_pathlib_iterdir()run_os_listdir()
import glob
# These three lines return both files and directorieslist(p.glob('*'))list(p.glob('*/'))glob.glob('*')
# Whereas this returns only directoriesglob.glob('*/')
import os
def get_subdirs(dir):"Get a list of immediate subdirectories"return next(os.walk(dir))[1]
def get_subfiles(dir):"Get a list of immediate subfiles"return next(os.walk(dir))[2]
def get_dirlist(rootdir):
dirlist = []
with os.scandir(rootdir) as rit:for entry in rit:if not entry.name.startswith('.') and entry.is_dir():dirlist.append(entry.path)
dirlist.sort() # Optional, in case you want sorted directory namesreturn dirlist
递归版本看起来像这样:
def get_dirlist(rootdir):
dirlist = []
with os.scandir(rootdir) as rit:for entry in rit:if not entry.name.startswith('.') and entry.is_dir():dirlist.append(entry.path)dirlist += get_dirlist(entry.path)
dirlist.sort() # Optional, in case you want sorted directory namesreturn dirlist
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 ;")
import os
def get_sub_directory_paths(start_directory, sub_directories):"""This method iterates through all subdirectory paths of a givendirectory to collect all directory paths.
:param start_directory: The starting directory path.:param sub_directories: A List that all subdirectory paths will bestored 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
import os
path = os.getcwd()
pathObject = os.walk(path)
这个路径对象是一个对象,我们可以通过以下方式获得一个数组
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]) ....]
from pathlib import Pathfrom glob import glob
current_dir = Path.cwd()all_sub_dir_paths = glob(str(current_dir) + '/*/') # returns list of sub directory paths
all_sub_dir_names = [Path(sub_dir).name for sub_dir in all_sub_dir_paths]