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

Home Posts Topics Members FAQ

Hack with os.walk()


Hello,

Have a look at this recursive function:

def walkDirectory( directory, element ):

element = element.newChil d( None, "directory" , None ) # automatically
appends to parent
element.setProp ( "name", os.path.basenam e(directory))

for root, dirs, files in os.walk( directory ):

for fileName in files:
element.addChil d( parseFile( os.path.join( root, fileName ))

for dirName in filter( acceptDirectory , dirs):
walkDirectory( os.path.join( root, dirName ), element )

return ### Note, this is inside for loop

What it does, is it recurses through all directories, and, with libxml2's
bindings, builds an XML document which maps directly to the file hierarchy.
For every file is parseFile() called, which returns a "file element" which is
appended; the resulting structure looks the way one expect -- like a GUI tree
view.

The current code works, but I find it hackish, and it probably is inefficient,
considering that os.walk() is not called once(as it usually is), but for
every directory level.

My problem, AFAICT, with using os.walk() the usual way, is that in order to
construct the /hierarchial/ XML document, I need to be aware of the directory
depth, and a recursive function handles that nicely; os.walk() simply
concentrates on figuring out paths to all files in a directory, AFAICT.

I guess I could solve it with using os.walk() in a traditional way, by somehow
pushing libxml2 nodes on a stack, after keeping track of the directory levels
etc(string parsing..). Or, one could write ones own recursive directory
parser..

My question is: what is the least ugly? What is the /proper/ solution for my
problem? How would you write it in the cleanest way?
Cheers,

Frans

Jul 18 '05 #1
0 1318

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

Similar topics

9
2908
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 files: print( "file:" + os.path.join(root, filename) ) for dirname in dirs:
6
4683
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 only walk one drive at a time (C:\, D:\, etc.). Is there a way to make os.walk() behave on Windows as it behaves on Linux? I'd like to walk the entire file system at once... not one drive at a time. Thanks!
7
4544
by: KraftDiner | last post by:
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
6
5913
by: Bruce | last post by:
Hi all, I have a question about traversing file systems, and could use some help. Because of directories with many files in them, os.walk appears to be rather slow. I`m thinking there is a potential for speed-up since I don`t need os.walk to report filenames of all the files in every directory it visits. Is there some clever way to use os.walk or another tool that would provide functionality like os.walk except for the listing of the...
9
2868
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
2
4017
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", len(files), "non-directory files" if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories
2
3014
by: Martin Marcher | last post by:
Hello, I'm playing around with os.walk and I made up del_tree(path) which I think is correct (in terms of the algorithm, but not as python wants it :)). As soon as some directory is deleted the iterator of os.walk chokes. OK that is somehow clear to me as it can't be valid anymore since it can't go to the just deleted directory but it is in the iterator.
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
2459
by: Jeff Nyman | last post by:
Greetings all. I did some searching on this but I can't seem to find a specific solution. I have code like this: ========================================= def walker1(arg, dirname, names): DC_List.append((dirname,'')) os.path.walk('\\\\vcdcflx006\\Flex\\Sites', walker1, 0)
1
8516
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7353
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...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5642
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
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2743
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
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
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.