This library provides a class for managing a filesystem tree. Test fixture is the driving use-case.
filesystem_tree is available on GitHub and on PyPI:
$ pip install filesystem_tree
We test against Python 2.6, 2.7, 3.2, and 3.3.
filesystem_tree is MIT-licensed.
Represent a filesystem tree.
Parameters: |
|
---|
Create a new instance of this class every time you need an isolated filesystem tree:
>>> fs = FilesystemTree()
This creates a temporary directory, the path to which you can access with fs.root:
>>> isdir(fs.root)
True
The prefix to use when making a temporary directory as root.
The root of the filesystem tree that this object represents.
Whether or not to automatically dedent file contents on write.
Builds a filesystem tree in root based on treedef.
Parameters: |
|
---|---|
Raises : | TypeError, if treedef contains anything besides strings and tuples; ValueError, if treedef contains a tuple that doesn’t have two or three items |
Returns: | None |
This method iterates over the items in treedef, creating directories for any strings, and files for any tuples. For file tuples, the first item is the path of the file, the second is the contents to write, and the third (optional) item is whether to dedent the contents first before writing it. All paths must be specified using / as the separator (they will be automatically converted to the native path separator for the current platform). Any intermediate directories will be created as necessary.
So for example if you instantiate a FilesystemTree:
>>> fs = FilesystemTree()
And you call mk with:
>>> fs.mk(('path/to/file.txt', 'Greetings, program!'))
Then you’ll have one file in your tree:
>>> os.listdir(os.path.join(fs.root, 'path', 'to'))
['file.txt']
And it will have the content you asked for:
>>> open(fs.resolve('path/to/file.txt')).read()
'Greetings, program!'
The automatic dedenting is so you can use multi-line strings in indented code blocks to specify file contents and indent it with the rest of your code, but not have the indents actually written to the file. For example:
>>> def foo():
... fs.mk(('other/file.txt', '''
... Here is a list of things:
... - Thing one.
... - Thing two.
... - Thing three.
... '''))
...
>>> foo()
>>> print(open(fs.resolve('other/file.txt')).read())
Here is a list of things:
- Thing one.
- Thing two.
- Thing three.