473,657 Members | 2,771 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3725
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
9361
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 structure, no? Also,it generates the below error during the os.renames section, but the odd thing is that it actually renames the files before saying it can't find them. Any ideas are welcomed. If I'm doing something *really* wrong here, just let me...
9
4072
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 already created :/ how to do it? thx.
3
2597
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 maintain or add features to. I'd like to have a function that builds a list of files with os.walk() and then have other functions accept that list as a parameter and modify it as needed. For example, if the user has specified that certain files...
5
3767
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 about other os.walk issues, but I think I need to back up to the basics or find another tool as this isn't going anywhere fast... I've tried this: for root, dirs, files in os.walk(path, topdown=True): file_skip_list = dir_skip_list =
3
1596
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 = {} tDicKey = tDicKey.append(folderKey)
43
3354
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 this case, just zeros (though I just to prove whatever ends up working, having a counting generator would be nice). The target syntax would be something like >>> a,b,c = zeros() >>> q,r,s,t,u,v = zeros()
9
2867
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') for file in dir: if (isdir(file)): # get the full path of the file
0
2033
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 more examples that may help, using os.walk: .... for j in i + i: .... print os.path.join(i, j) .... /var/log/apache2
4
3729
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
8394
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8306
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8825
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8605
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7327
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5632
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4304
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1615
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.