473,396 Members | 1,608 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,396 software developers and data experts.

should os.walk return a list instead of a tuple?

Hello,

os.walk doc: http://www.python.org/doc/2.4/lib/os....html#l2h-1625

When walking top to bottom, it allows you to choose the directories you
want to visit dynamically by changing the second parameter of the tuple
(a list of directories). However, since it is a tuple, you cannot use
"filter" on it, since it would mean reassigning it:

for dir_tuple in os.walk('/home'):
dir_tuple[1]=filter(lambda x: not x.startswith('.'), dir_tuple[1])
#do not show hidden files
print dir_tuple #just print the directory and its contents in the
simplest possible way

If os.walk did return a list of three items instead of a tuple, that
would become possible. It would also not break old code like
for dirpath, dirnames, filenames in os.walk(somedir):
do something.....
Since assigning a list to a tuple is valid python code.

Thanks.
Mar 21 '06 #1
2 3707
Ministeyr wrote:
When walking top to bottom, it allows you to choose the directories
you want to visit dynamically by changing the second parameter of the
tuple (a list of directories). However, since it is a tuple, you
cannot use "filter" on it, since it would mean reassigning it:

for dir_tuple in os.walk('/home'):
dir_tuple[1]=filter(lambda x: not x.startswith('.'),
dir_tuple[1])
#do not show hidden files
print dir_tuple #just print the directory and its
contents in the
simplest possible way

If os.walk did return a list of three items instead of a tuple, that
would become possible.


But you don't need to assign to it, you simply need to mutate it:

for dir, subdirs, files in os.walk('/home'):
subdirs[:] = [d for d in subdirs if not d.startswith('.')]
print dir, subdirs, files

(and if you are desparate to use filter+lambda that works as well.)
Mar 21 '06 #2
Ministeyr wrote:
Hello,

os.walk doc: http://www.python.org/doc/2.4/lib/os....html#l2h-1625

When walking top to bottom, it allows you to choose the directories you
want to visit dynamically by changing the second parameter of the tuple
(a list of directories). However, since it is a tuple, you cannot use
"filter" on it, since it would mean reassigning it:

for dir_tuple in os.walk('/home'):
dir_tuple[1]=filter(lambda x: not x.startswith('.'),
dir_tuple[1]) #do not show hidden files
print dir_tuple #just print the directory and its contents in
the simplest possible way


Ok, you are missing 2 points here :
1/ multiple assignment. Python allows you to do things like:
a, b, c = (1, 2, 3)

So the canonical use of os.walk is:
for dirpath, subdirs, files in os.walk(path):
...

2/ what's mutable and what is not: a tuple is immutable, but a list is
not. The fact that the list is actually an element of a tuple doesn't
make it immutable:
t = ('A', [1, 2, 3])
t ('A', [1, 2, 3]) t[1] [1, 2, 3] # this will work
t[1].append(4)
t ('A', [1, 2, 3, 4]) # this won't work
t[1] = [] Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: object does not support item assignment


HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom.gro'.split('@')])"
Mar 21 '06 #3

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: Yomanium Yoth Taripoät II | last post by:
HI, 1) what are the differences between list and tuple? 2) how to concatenate tuple and list? no method, no opérator? 3) im looking the fucking manual, and cant add value in my tuple, when it...
3
by: rbt | last post by:
I'm trying to write very small, modular code as functions to break up a big monolithic script that does a file system search for particular strings. The script works well, but it's not easy to...
5
by: rbt | last post by:
Could someone demonstrate the correct/proper way to use os.walk() to skip certain files and folders while walking a specified path? I've read the module docs and googled to no avail and posted here...
3
by: ina | last post by:
I want to walk a folder structor and group all the files by extention. Here is the code I put together is there a better way of doing this? <code> import os folderKey = "Folders" dicExt = {}...
43
by: Tim Chase | last post by:
Just as a pedantic exercise to try and understand Python a bit better, I decided to try to make a generator or class that would allow me to unpack an arbitrary number of calculatible values. In...
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') ...
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...
4
by: tdahsu | last post by:
Hi, I'm using os.walk as follows: (basedir, pathnames, files) = os.walk("results", topdown=True) and I'm getting the error: ValueError: too many values to unpack
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.