Last active
March 9, 2016 09:13
-
-
Save cstrap/f86fc286d997a995cb1f to your computer and use it in GitHub Desktop.
Sample of "null writing" to file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| import io | |
| class File(io.FileIO): | |
| def __init__(self, name, mode='r', closefd=True, **kwargs): | |
| self.wf = kwargs.pop('wf', True) | |
| super(File, self).__init__(name, mode, closefd) | |
| def write(self, line,*args, **kwargs): | |
| if self.wf: | |
| super(File, self).write(line) | |
| if __name__ == '__main__': | |
| """ | |
| foo.txt has some rows | |
| if `wf=True` class makes a copy of `foo.txt` in `bar.txt` | |
| """ | |
| with File('foo.txt', 'r') as foo: | |
| with File('bar.txt', 'w', wf=True) as bar: | |
| for line in foo: | |
| bar.write(line) | |
| """ | |
| foo.txt has some rows | |
| if `wf=False` make a touch of `baz.txt` and the class doesn't write lines | |
| """ | |
| with File('foo.txt', 'r') as foo: | |
| with File('baz.txt', 'w', wf=False) as bar: | |
| for line in foo: | |
| bar.write(line) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment