Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python os.path.walk() method

Tags:

python

I'm currently using the walk method in a uni assignment. It's all working fine, but I was hoping that someone could explain something to me.

in the example below, what is the a parameter used for on the myvisit method?

>>> from os.path import walk
>>> def myvisit(a, dir, files):
...   print dir,": %d files"%len(files)

>>> walk('/etc', myvisit, None)
/etc : 193 files
/etc/default : 12 files
/etc/cron.d : 6 files
/etc/rc.d : 6 files
/etc/rc.d/rc0.d : 18 files
/etc/rc.d/rc1.d : 27 files
/etc/rc.d/rc2.d : 42 files
/etc/rc.d/rc3.d : 17 files
/etc/rc.d/rcS.d : 13 files
like image 316
Aaron Moodie Avatar asked May 29 '10 07:05

Aaron Moodie


People also ask

What is a walk function?

The walk function generates the file names in a directory tree by navigating the tree in both directions, either a top-down or a bottom-up transverse. Every directory in any tree of a system has a base directory at its back. And then it acts as a subdirectory.

What is the difference between os Listdir () and os walk?

listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.

How do you use Listdir in Python?

listdir() method in python is used to get the list of all files and directories in the specified directory. If we don't specify any directory, then list of files and directories in the current working directory will be returned.

What function allows the program to walk through all of the folders in a path?

walk() is a built-in Python method that generates the file names in the file index tree by walking either top-down or bottom-up. Each directory in the tree rooted at the directory top generates a 3-tuple, which are dirpath, dirnames, and filenames.


2 Answers

The first argument to your callback function is the last argument of the os.path.walk function. Its most obvious use is to allow you to keep state between the successive calls to the helper function (in your case, myvisit).

os.path.walk is a deprecated function. You really should use os.walk, which has no need for either a callback function or helper arguments (like a in your example).

for directory, dirnames, filenames in os.walk(some_path):
    # run here your code
like image 126
tzot Avatar answered Sep 21 '22 21:09

tzot


It's the argument you gave to walk, None in the example in your question

like image 24
Krumelur Avatar answered Sep 18 '22 21:09

Krumelur