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.
You can also pass .name of the file object but then you should close the file by hand before function reopens it from the name.
import sys
def takes_filename(fn):
print('Name of file is', fn)
myfile = open(sys.argv[0])
myfile.close()
takes_filename(myfile.name)
assert myfile.name == sys.argv[0]
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
You can also pass .name of the file object but then you should close the file by hand before function reopens it from the name.
import sys
def takes_filename(fn):
print('Name of file is', fn)
myfile = open(sys.argv[0])
myfile.close()
takes_filename(myfile.name)
assert myfile.name == sys.argv[0]
Yes, to be more precise, I had this idea after this discussion http://www.daniweb.com/software-development/python/threads/363125 which used a temporary postscript file. Here is how one could write a function to save a tkinter canvas
def save_image(tk_canvas, image_filename):
with autofilename(suffix=".eps") as name: # use a temporary .eps file
tk_canvas.postscript(file=name)
subprocess.Popen("convert {0} {1}".format(name, image_filename), shell=True).wait()
Here, the context permits to create a temporary postscript file on the fly without worrying about its lifetime.
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691
In a similar vein, here is a context to create an automatically deleted temporary directory
@contextmanager
def autodirname(suffix='', prefix='tmp', dir=None, delete=True, ignore_errors=False, onerror=None):
"""This context creates a visible temporary directory in the file system.
This directory is removed by default when the context exits (delete = True).
The parameters ignore_error and onerror have the same meaning as in shutil.rmtree()
"""
from tempfile import mkdtemp
name = mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
try:
yield name
finally:
if delete:
from shutil import rmtree
rmtree(name, ignore_errors) if onerror is None else rmtree(name, ignore_errors, onerror)
Gribouillis
Posting Maven
2,786 posts since Jul 2008
Reputation Points: 1,044
Solved Threads: 691