This snippet defines a context
autofilename() to create an existing temporary file with a new name in python. Unlike the methods in the
tempfile module, it only gives a filename which exists within a 'with' block, instead of an open file. This is useful for example when a program needs to pass a new filename to a function which does not accept a file object argument. As with the tempfile module, there should be no race condition between processes on the temporary file creation.
# 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. """
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.