473,387 Members | 1,502 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

A little assistance with os.walk please.

The os.walk function walks the operating systems directory tree.

This seems to work, but I don't quite understand the tupple that is
returned...
Can someone explain please?

for root, dirs, files in os.walk('/directory/'):
print root
# print dirs
# print files

Aug 14 '06 #1
7 4519
On Mon, 14 Aug 2006 07:44:39 -0700, KraftDiner wrote:
The os.walk function walks the operating systems directory tree.

This seems to work, but I don't quite understand the tupple that is
returned...
Can someone explain please?

for root, dirs, files in os.walk('/directory/'):
print root
# print dirs
# print files
>>print os.walk.__doc__
Directory tree generator.

For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple

dirpath, dirnames, filenames

dirpath is a string, the path to the directory. dirnames is a list of
the names of the subdirectories in dirpath (excluding '.' and '..').
filenames is a list of the names of the non-directory files in dirpath.
Note that the names in the lists are just names, with no path components.
To get a full path (which begins with top) to a file or directory in
dirpath, do os.path.join(dirpath, name).

If optional arg 'topdown' is true or not specified, the triple for a
directory is generated before the triples for any of its subdirectories
(directories are generated top down). If topdown is false, the triple
for a directory is generated after the triples for all of its
subdirectories (directories are generated bottom up).

When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
subdirectories whose names remain in dirnames; this can be used to prune
the search, or to impose a specific order of visiting. Modifying
dirnames when topdown is false is ineffective, since the directories in
dirnames have already been generated by the time dirnames itself is
generated.

By default errors from the os.listdir() call are ignored. If
optional arg 'onerror' is specified, it should be a function; it
will be called with one argument, an os.error instance. It can
report the error to continue with the walk, or raise the exception
to abort the walk. Note that the filename is available as the
filename attribute of the exception object.

Caution: if you pass a relative pathname for top, don't change the
current working directory between resumptions of walk. walk never
changes the current directory, and assumes that the client doesn't
either.

Example:

from os.path import join, getsize
for root, dirs, files in walk('python/Lib/email'):
print root, "consumes",
print sum([getsize(join(root, name)) for name in files]),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
Aug 14 '06 #2
The os.walk function walks the operating systems directory tree.

Yup.
This seems to work, but I don't quite understand the tupple that is
returned...
Can someone explain please?

for root, dirs, files in os.walk('/directory/'):
print root
# print dirs
# print files

As cheesy as it may sound, try uncommenting the two commented
lines. For a more explicit variant:

print repr(dirs)
print repr(files)

You'll notice that they're lists.

In the directory "root", you'll find the subdirectories given in
the list "dirs" and you'll find the files given in the list "files".

-tkc

Aug 14 '06 #3
KraftDiner wrote:
The os.walk function walks the operating systems directory tree.

This seems to work, but I don't quite understand the tupple that is
returned...
Can someone explain please?

for root, dirs, files in os.walk('/directory/'):
print root
# print dirs
# print files
Actually returns two tuples: dirs and files

root - is the directory branch you are currently walking
dirs - are the directory branches that are subdirectories of this
directory branch
files - are the files that live in this directory branch
To process all the files here you do something like:

for afile in files: # resist the urge to call it 'file'
fullpath=os.path.join(root, afile)
#
# Do something with fullpath
#

Hard to figure out item - If you wish to NOT process some of the
dirs, you can delete them from the dirs list here and they won't
get walked. You MUST delete them in place with del dirs[n] or
dirs.pop or some other function that deletes in-place.

You might want to type: help(os.walk) to get some more info.

-Larry Bates
Aug 14 '06 #4

Larry Bates wrote:
KraftDiner wrote:
The os.walk function walks the operating systems directory tree.

This seems to work, but I don't quite understand the tupple that is
returned...
Can someone explain please?

for root, dirs, files in os.walk('/directory/'):
print root
# print dirs
# print files

Actually returns two tuples: dirs and files

root - is the directory branch you are currently walking
dirs - are the directory branches that are subdirectories of this
directory branch
files - are the files that live in this directory branch
To process all the files here you do something like:

for afile in files: # resist the urge to call it 'file'
fullpath=os.path.join(root, afile)
#
# Do something with fullpath
#

Hard to figure out item - If you wish to NOT process some of the
dirs, you can delete them from the dirs list here and they won't
get walked. You MUST delete them in place with del dirs[n] or
dirs.pop or some other function that deletes in-place.

You might want to type: help(os.walk) to get some more info.
Yep done that. Thanks.
Two things..
1) there seems to be an optional topdown flag. Is that passed to
os.walk(path, topdownFlag)
2) I only want to process files that match *.txt for example... Does
that mean I need to parse the list of files for the .txt extention or
can I pass a wildcard in the path parameter?

-Larry Bates
Aug 14 '06 #5
1) there seems to be an optional topdown flag. Is that passed to
os.walk(path, topdownFlag)
Yes.
2) I only want to process files that match *.txt for example... Does
that mean I need to parse the list of files for the .txt extention or
can I pass a wildcard in the path parameter?
>>for path, dirs, files in os.walk("."):
.... for f in files:
.... if not f.lower().endswith(".txt"): continue
.... print os.path.join(path, f)

If you want to be more complex:

>>from os.path import splitext
allowed = ['.txt', '.sql']
for path, dirs, files in os.walk("."):
.... for f in files:
.... if splitext(f)[1].lower() not in allowed: continue
.... fn = os.path.join(path, f)
.... print "do something with %s" % fn
Just a few ideas,

-tkc


Aug 14 '06 #6

Tim Chase wrote:
1) there seems to be an optional topdown flag. Is that passed to
os.walk(path, topdownFlag)

Yes.
2) I only want to process files that match *.txt for example... Does
that mean I need to parse the list of files for the .txt extention or
can I pass a wildcard in the path parameter?
>>for path, dirs, files in os.walk("."):
... for f in files:
... if not f.lower().endswith(".txt"): continue
... print os.path.join(path, f)

If you want to be more complex:

>>from os.path import splitext
>>allowed = ['.txt', '.sql']
>>for path, dirs, files in os.walk("."):
... for f in files:
... if splitext(f)[1].lower() not in allowed: continue
... fn = os.path.join(path, f)
... print "do something with %s" % fn
Just a few ideas,

-tkc

Many thanks all.
B.

Aug 14 '06 #7
>>allowed = ['.txt', '.sql']
>>for path, dirs, files in os.walk("."):
... for f in files:
... if splitext(f)[1].lower() not in allowed: continue
Additionally, if you really do want to specify wildcards:
>>allowed = ['*.txt', 'README*', '*.xml', '*.htm*']
from glob import fnmatch
import os
for path, dirs, files in os.walk("."):
.... good_files = []
.... for pat in allowed:
.... good_files.extend(fnmatch.filter(files, pat))
.... if good_files: break
.... for f in good_files:
.... print "doing something with %s" %
os.path.join(path, f)

-tkc



Aug 14 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: hokieghal99 | last post by:
This script is not recursive... in order to make it recursive, I have to call it several times (my kludge... hey, it works). I thought os.walk's sole purpose was to recursively walk a directory...
9
by: Marcello Pietrobon | last post by:
Hello, I am using Pyton 2.3 I desire to walk a directory without recursion this only partly works: def walk_files() : for root, dirs, files in os.walk(top, topdown=True): for filename in...
6
by: rbt | last post by:
More of an OS question than a Python question, but it is Python related so here goes: When I do os.walk('/') on a Linux computer, the entire file system is walked. On windows, however, I can...
1
by: sumanthsclsdc | last post by:
hello friends, i am using the os.path.walk to search to filter the files with the given word, this function i m using in many modules. i just want to place this function in some class...
9
by: silverburgh.meryl | last post by:
i am trying to use python to walk thru each subdirectory from a top directory. Here is my script: savedPagesDirectory = "/home/meryl/saved_pages/data" dir=open(savedPagesDirectory, 'r') ...
2
by: gregpinero | last post by:
In the example from help(os.walk) it lists this: from os.path import join, getsize for root, dirs, files in walk('python/Lib/email'): print root, "consumes", print sum(), print "bytes in",...
2
by: | last post by:
Hi everyone The following code: scriptPath = os.path.dirname(__file__) (dirpath, dirnames, filenames) = os.walk(scriptPath) print 'dirpath\n' print dirpath print 'dirnames\n'...
0
by: Jeff McNeil | last post by:
Your args are fine, that's just the way os.path.walk works. If you just need the absolute pathname of a directory when given a relative path, you can always use os.path.abspath, too. A couple...
3
by: gaurav92K | last post by:
sir i am working in a company . there are many pc. i want to use remote assistance. i configure all group policy which are related remote assistance.and i enable service through remote in system...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.