Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 os.walk() Method

Python3 os.walk() Method

Python3 OS File/Directory Methods Python3 OS File/Directory Methods


Overview

The os.walk() method creates a generator that yields all the files in the directory being searched and its subdirectories.

The os.walk() method outputs the file names in a directory by walking the directory tree upwards or downwards.

The os.walk() method is a simple and easy-to-use file and directory traverser that helps us handle files and directories efficiently.

Valid on Unix and Windows.

Syntax

The **walk()** method syntax 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:

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