I decided to write a tiny class to automatically write and delete a file given filename and content. It is intended to make testing IO less verbose. I include a small example usage.
temporary.py
import os
class Temporary:
def __init__(self, name, content):
self.name = name
self.content = content
def __enter__(self):
with open(self.name, 'w+') as f:
f.write(self.content)
def __exit__(self,_,__,___):
os.remove(self.name)
first_word.py
import doctest
from temporary import Temporary
def first_word_of_each_line(filename):
"""
>>> txt = '\\n'.join(['first line', 'second line', 'bar bar'])
>>> with Temporary('foo.txt', txt): first_word_of_each_line('foo.txt')
['first', 'second', 'bar']
"""
with open(filename) as f:
lines = f.read().splitlines()
return [line.split()[0] for line in lines]
if __name__ == "__main__":
doctest.testmod()
open
using something like pypi.python.org/pypi/mock – JaDogg May 19 at 17:28tempfile
module? – Gareth Rees May 21 at 14:07with
not intended to be used for serious purposes – Caridorc May 28 at 18:06