473,473 Members | 1,874 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

is there a better way to walk a file system?

ina
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)
dicExt[folderKey] = []

walkPath = r"\\zek\C$\AST"

for d in os.walk(walkPath):
(dirpath, dirnames, filenames) = d
dicExt[folderKey].append(dirpath)
for fname in filenames:
fs = os.path.splitext(fname)
if dicExt.has_key(fs[-1]):
dicExt[fs[-1]].append(os.path.join(dirpath,fname))
else:
dicExt[fs[-1]] = []
dicExt[fs[-1]].append(fname)
tDicKey.append(fs[-1])
for k in tDicKey:
print k +" "+ str(len(dicExt[k]))
</code>
Right now it is just prints out the counts.

Thanks

Erin

Jul 19 '05 #1
3 1580
ina wrote:
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>

[snip]

If you were to download Jason Orendorff's "path" module, which is a
convenient single-file package that vastly simplifies all manner of
dealings with directory and file names, I suspect your example code
could be reduced to less than half the number of lines it now uses, and
with a corresponding increase in readability and maintainability.

The answer to the question "is there a better way of doing this?" in
relation to paths is always "yes, use Jason Orendorff's path module".

-Peter
Jul 19 '05 #2
"Peter Hansen" wrote:
ina wrote:
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>


[snip]

If you were to download Jason Orendorff's "path" module, which is a
convenient single-file package that vastly simplifies all manner of
dealings with directory and file names, I suspect your example code
could be reduced to less than half the number of lines it now uses, and
with a corresponding increase in readability and maintainability.


Well, it's exactly half non-blank lines (10) and still readable; of
course it can be compressed more but we're not doing perl here <wink>.

import sys
from path import path
from itertools import groupby

def getExtension(aPath):
return aPath.ext

root = len(sys.argv) > 1 and sys.argv[1] or '.'
for ext,iterFiles in groupby(sorted(path(root).walkfiles(),
key=getExtension),
getExtension):
print "%s: %d files" % (ext, len(tuple(iterFiles)))
By the way, from this example I discovered that properties cannot be
unbound, i.e. using path.ext instead of getExtension raises TypeError.
Couldn't/shouldn't Class.prop(instance) be allowed as equivalent of
instance.prop, just as methods ?
The answer to the question "is there a better way of doing this?" in
relation to paths is always "yes, use Jason Orendorff's path module".

-Peter


George

Jul 19 '05 #3
George Sakkis wrote:
By the way, from this example I discovered that properties cannot be
unbound, i.e. using path.ext instead of getExtension raises TypeError.
Couldn't/shouldn't Class.prop(instance) be allowed as equivalent of
instance.prop, just as methods ?


Use the property's __get__() method instead:
class A(object): .... def __init__(self, value):
.... self._value = value
.... value = property(lambda self: self._value)
.... def __repr__(self): return "A(%r)" % self._value
.... a = A(42)
A.value.__get__(a) 42 sorted([A(42), A(2), A(4)], key=A.value.__get__)

[A(2), A(4), A(42)]

Peter

Jul 19 '05 #4

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

Similar topics

4
by: Florian Lindner | last post by:
Hello, when I'm walking through a file system hierarchy using os.walk, how can I get the full path of a file or dir? normpath and abspath don't work. Thx, Florian
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...
0
by: Fitzgerald Steele | last post by:
I had a software package screw up a directory tree by placing all the files in a directory of the same name. So I wound up with: Root file1.txt (dir) file1.txt (file) file2.txt (dir)...
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...
6
by: Darren | last post by:
X-No-Archive Hi all, Can anyone help me with structuring the data in a small tool I have to build? I'm trying to work out if there's a design pattern or data structure that would remove some...
8
by: Andre Meyer | last post by:
Hi all os.walk() is a nice generator for performing actions on all files in a directory and subdirectories. However, how can one use os.walk() for walking through two hierarchies at once? I want...
1
by: schellu | last post by:
i'm new to python script , i'm getting following error while executing AttributeError: class 'org.python.modules.os' has no attribute 'walk' my code is : class Client(Object): def...
2
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...
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...
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
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
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,...
0
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...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
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 ...
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
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...

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.