Object Path module (op) for Python
use at your own risk :-)
download zip file
Object Path module for Python2.1
by Jens Peter Grosen (jp@grosen.dk)
op.py main module
optester.py unit test
op.html pydoc documentation
OPTest folder with files, used by the unittest
To run the unittest you have to edit optester.py with the path to the OPTest directory.
Examples of use
>>> # create a new object path
>>> p = op.path(r"""d:\dev""")
>>> p
d:\dev
>>> p.isdir()
1
>>> # create new path
>>> py = p.path("py", "modules")
>>> py
d:\dev\py\modules
>>> py.isdir()
1
>>> file = py.path("op.py")
>>> file.isfile()
1
>>> file
d:\dev\py\modules\op.py
>>> file.name()
'op.py'
>>> file.ext()
'.py'
>>> file.size()
10552
>>> # count lines using op
>>> len(file.readlines())
318
>>> #count lines useing standard lib.
>>> f = open(file.str())
>>> len(f.readlines())
318
>>> f.close()
>>>
>>> #reading/writing
>>> #make a new file and return a path object for it
>>> log = op.newfile(r"""d:\log.txt""")
>>> #write to the file
>>> print >> log, "hello"
>>> print >> log, "python"
>>> # show content of the file
>>> log.readlines()
['hello\n', 'python\n']
>>> log.empty()
>>> log.readlines()
[]
>>> print >> log, "first line"
>>> log.readlines()
['first line\n']
Notice that you do not have to close the file and therefore there is no need to use exception handling to ensure that close is always called.
>>> #directory list handling
>>> p = op.path(r"""c:\tools\python21""")
>>> # show the size of the first 5 files or dirs in python21
>>> for f in p.list()[:5]:
... print f.name(), "\tsize", f.size()
...
as_pydoc size 23294
changes-ActivePython.txt size 874
DLLs size 2257583
Documentation size 5890677
Downloads size 0
>>> # show all python files in the dir
>>> for f in p.list("*.py"):
... print f.name(), "\tsize", f.size()
...
pyppm.py size 1506
>>> #count the number of python files in all subdirs
>>> len(p.listall("*.py"))
874
>>> # show files with more than 1000 linies
>>> for f in p.listall("*.py"):
... if len(f.readlines())>1000:
... print f.name(), "\tlines:", len(f.readlines()), "\tsize", f.size()
...
doctest.py lines: 1118 size 37623
imaplib.py lines: 1125 size 35135
mhlib.py lines: 1003 size 34261
pydoc.py lines: 1878 size 77771
urllib.py lines: 1383 size 48972
urllib2.py lines: 1138 size 38592
ccompiler.py lines: 1046 size 44079
dist.py lines: 1075 size 43089
Tix.py lines: 1266 size 47110
Tkinter.py lines: 3086 size 136082
pycodegen.py lines: 1267 size 40641
transformer.py lines: 1304 size 43336
texi2html.py lines: 1613 size 53582
commctrl.py lines: 1530 size 51056
win32con.py lines: 4468 size 120524
winerror.py lines: 1490 size 48520
winnt.py lines: 1094 size 36727