Python3 os.walk() Method

Python3 OS 文件/目录方法Python3 OS File/Directory Methods


Overview

The os.walk() method can create a generator to generate all files in the directory to be searched and its subdirectories.

The os.walk() method is used to output the file names in a directory by walking through the directory tree, either top-down or bottom-up.

The os.walk() method is a simple and easy-to-use file and directory traversal iterator that can help us efficiently handle file and directory related tasks.

Valid on Unix and Windows.

Syntax

walk()The method syntax is as follows:

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

Parameters

  • top-- For every folder under the root directory (including itself), it yields a 3-tuple (dirpath, dirnames, filenames) [folder path, folder names, file names].

  • topdown-- Optional. If True or not specified, a directory's 3-tuple will be generated before any of its subfolders' 3-tuples (top-down). If topdown is False, a directory's 3-tuple will be generated after any of its subfolders' 3-tuples (bottom-up).

  • onerror-- Optional. It is a function; it is called with one argument, an OSError instance. After reporting this error, continue walking, or raise an exception to terminate the walk.

  • followlinks-- If set to true, directories are accessed through symbolic links.

Return Value

Returns a generator.

Example

The following example demonstrates the use of the walk() method:

Example

#!/usr/bin/python3

import os
for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))

The output of the above program is:

./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp
./tmp/test.py

Python3 OS 文件/目录方法Python3 OS File/Directory Methods

Other Extensions