# python >= 2.5 from __future__ import with_statement from contextlib import contextmanager from tempfile import mkstemp import os @contextmanager def autofilename(suffix='', prefix='tmp', dir=None, delete=True): """This context creates a visible temporary file with size 0 in the file system. This file is removed by default when the context exits (delete = True). Unlike the tempfile module, this context only offers a filename (and not an open file) to the code that uses it. """ fd, name = mkstemp(suffix=suffix, prefix=prefix, dir=dir) try: os.close(fd) yield name finally: if delete: try: os.remove(name) except OSError: pass # USE CASE if __name__ == "__main__": def report(filename): print("file '%s' exists: %s" % (filename, "yes." if os.path.exists(name) else "no.")) with autofilename() as name: report(name) # check that a file with that name exists in the system # use the filename temporarily with open(name, "w") as f_out: f_out.write("hello world") with open(name, "r") as f_in: print(f_in.read()) # after the with block, the file was deleted in the system report(name) """ my output --> file '/tmp/tmpAzHfIz' exists: yes. hello world file '/tmp/tmpAzHfIz' exists: no. """
Edited 5 Years Ago by pyTony: n/a
Edited 5 Years Ago by Gribouillis: n/a