Latest web development tutorials

Python os.walk () method

Python File (File) method Python OS file / directory methods


Outline

os.walk () method is used by migratory species in the directory in the output files in the directory name, up or down.

In Unix, Windows effectively.

grammar

walk () method syntax is as follows:

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

parameter

  • top - Each file in the root folder (including its own) to give 3-tuple (dirpath, dirnames, filenames) [folder path, the folder name, file name].

  • topdown - optional, or not specified as True, a list of 3-tuples than 3- tuple of its sub-folders created in the first (top-down table of contents).If topdown is False, 3- tuples than produce a directory (the directory from bottom to top) after 3- tuple of its sub-folders.

  • onerror - optional, it is a function; it has a parameter called a OSError instance.Report this error, continue to walk, or throw an exception terminated walk.

  • followlinks - is set to true, then through the soft link to access the directory.

return value

This method has no return value.

Examples

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

#!/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 above program output 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 (File) method Python OS file / directory methods