FileWrapper Input Parser
back to 'in and out'

This document decribes an input parser which is used to wrap another input parser and provide it with the source read from a file path provided as the source attribute to a Twiddler.

Here's a simple example, where first we create the source file on disk:

>>> f = open(test_path,'w')
>>> f.write('<node id="test">my node</node>')
>>> f.close()

Now we create a Twiddler from it:

>>> from twiddler import Twiddler
>>> from twiddler.input.default import Default
>>> from twiddler.input.filewrapper import FileWrapper
>>> t = Twiddler(test_path,input=FileWrapper(Default))
>>> t['test'].replace('My test value')
>>> print t.render()

<node id="test">My test value</node>

If no input is specified to the FileWrapper constructor, the default input will be used:

>>> t = Twiddler(test_path,input=FileWrapper())
>>> t['test'].replace('My test value')
>>> print t.render()

<node id="test">My test value</node>

You can also specify a path to prefix to the path provided to the Twiddler constructor:

>>> import os
>>> f = open(os.path.join(test_dir,'test.twiddler'),'w')
>>> f.write('<test_content/>')
>>> f.close()
>>> t = Twiddler('test.twiddler',input=FileWrapper(Default,test_dir))
>>> print t.render()

<test_content />

Finally, you can specify a file path as the prefix. If specified, the directory containing this file will be used as the prefix. This is handy when trying to open source files that are located relative to the file in which the Twiddler is being constructed.

For example, filewrapper.txt is located in the 'input' sub-package of the Twiddler library, so to open the 'test.twiddler' file in the 'test' sub-package, we would do the following:

>>> t = Twiddler('../tests/test.twiddler',input=FileWrapper(Default,__file__))
>>> print t.render()

<html>
<body>
<h1 id="header" />
<p id="content">
</p>
</body>
</html>

In addition to being able to specify the prefix, you can also specify the character set with which the file is encoded.

First, lets create an encoded file:

>>> f = open(test_path,'w')
>>> f.write(u'<node id="test">\xa3</node>'.encode('utf-8'))
>>> f.close()

Now we can use it with a FileWrapper:

>>> t = Twiddler(test_path,input=FileWrapper(encoding='utf-8'))
>>> t.render()

u'<node id="test">\xa3</node>'

changed August 1, 2008