OPath: Python directory and file tree object encapsulation¶
OPath is a library for encapsulating directory and file trees. It makes creating, moving, and deleting directories and files a breeze.
Build/Coverage Status¶
OPath is currently in development (Version 0.5.1)
Branch | Build | Coverage |
---|---|---|
master | ||
development |
Installation¶
Its suggested you use pipenv to install OPath.
OPath can be downloaded from https://github.com/jvrana/opath.
Option 1: pipenv
To install, just cd into your project and run. Make sure to review how to use pipenv.
pipenv install opath
To install your project to the virtual environment
Option 2: pip
If you want to use pip, cd into the OPath directory and run
pip install .
Usage¶
Use add
to create folders.
from opath import *
env = ODir('bin')
env.add('subfolder1')
env.add('subfolder2')
env.print()
>>>
*bin
| *subfolder1
| *subfolder2
Functions return ODir objects and so can be chained together.
env = ODir('bin')
env.add('subfolder1').add('subsubfolder')
env.print()
>>>
*bin
| *subfolder1
| | *subsubfolder
Files can be written quickly
env = ODir('bin')
env.add('subfolder1').add('subsubfolder')
env.subsubfolder.write('My Data', 'w')
Or a OFile can be added:
env = ODir('bin')
env.add_file('myfile.txt', attr='myfile')
env.myfile.write('this is my data', 'w')
Folders create accesible ODir attributes automatically. Alternative attribute names can be set using ‘alias=’
env = ODir('bin')
env.add('subfolder1')
env.subfolder1.add('misc')
env.subfolder1.misc.add('.hidden', alias='hidden')
env.subfolder1.misc.hidden.add('hiddenbin')
env.print()
*bin
| *subfolder1
| | *misc
| | | *.hidden ("hidden")
| | | | *hiddenbin
By default, attributes are pushed back the the root directory. The following is equivalent to above.
env = ODir('bin')
env.add('subfolder1')
env.subfolder1.add('misc')
env.misc.add('.hidden', alias='hidden')
env.hidden.add('hiddenbin')
env.print()
*bin
| *subfolder1
| | *misc
| | | *.hidden ("hidden")
| | | | *hiddenbin
Making, moving, copying, and deleting directories¶
The location of the root folder can be set by set_bin
env.set_bin('../bin')
Directories can be created, deleted, copied or moved using mkdirs
,
cpdirs
, mvdirs
, rmdirs
env.mkdirs()
env_copy = env.cpdirs()
# you can do stuff with env_copy independently
env.mvdirs('~/Document')
env_copy.rmdirs()
Advanced usage¶
All iterables return special list-like objects that can be chained in one-liners.
env.descendents() # returns a ChainList object
# find all txt files
env.descendents(include_self=True).glob("*.txt")
# recursively change permissions for directories
env.abspaths.chmod(0o444)