Easy Tutorial
❮ Ref Math Fabs Python Att List Len ❯

Python3 os.walk() Method

Python3 OS File/Directory Methods


Overview

The os.walk() method generates the file names in a directory tree by walking either top-down or bottom-up.

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

The os.walk() method is a simple and easy-to-use file and directory traverser, which helps us efficiently handle file and directory-related tasks.

Valid in Unix, Windows.

Syntax

The syntax for the walk() method is as follows:

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

Parameters

Return Value

Returns a generator.

Example

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

#!/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))

Executing the above program outputs the following:

./.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 File/Directory Methods

❮ Ref Math Fabs Python Att List Len ❯