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

Python os.walk() method

Python os.walk() method

Python File methods Python OS file/directory methods


Overview

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

- root is the address of the folder itself that is currently being traversed - dirs is a list containing the names of all directories in that folder (excluding subdirectories) - files is likewise a list containing the names of all files in that folder (excluding subdirectories)

Return Value

Returns a generator.

Example

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

Example

#!/usr/bin/python

-- coding: UTF-8 --

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

Python File methods Python OS file/directory methods