help with using temporary files
Jeremy Jones
zanesdad at bellsouth.net
Tue Nov 22 11:19:07 EST 2005
Gerard Flanagan wrote:
>Hello
>
> I'm sure its basic but I'm confused about the error I get with the
>following code. Any help on basic tempfile usage?
>
>
>ActivePython 2.4.1 Build 247 (ActiveState Corp.) based on
>Python 2.4.1 (#65, Jun 20 2005, 17:01:55) [MSC v.1310 32 bit (Intel)]
>on win32
>Type "help", "copyright", "credits" or "license" for more information.
>
>
>>>>from tempfile import NamedTemporaryFile
>>>>
>>>>tmp = NamedTemporaryFile()
>>>>tmp.write("Hello")
>>>>tmp.close()
>>>>
>>>>print tmp.name
>>>>
>>>>
>c:\docume~1\gerard\locals~1\temp\tmpxqn4yl
>
>
>>>>f = open(tmp.name)
>>>>
>>>>
>Traceback (most recent call last):
> File "<stdin>", line 1, in ?
>IOError: [Errno 2] No such file or directory:
>'c:\\docume~1\\gerard\\locals~1\\temp\\tmpxqn4yl'
>
>
>Thanks
>
>Gerard
>
>
>
It gets created:
In [24]: import tempfile
In [25]: t = tempfile.NamedTemporaryFile()
In [26]: t.name
Out[26]: '/tmp/tmp9bmhap'
In [27]: ls -l /tmp/tmp*
-rw------- 1 jmjones jmjones 0 Nov 22 11:15 /tmp/tmp9bmhap
In [28]: t.write("123")
In [29]: t.flush()
In [30]: ls -l /tmp/tmp*
-rw------- 1 jmjones jmjones 3 Nov 22 11:15 /tmp/tmp9bmhap
In [31]: t.close()
In [32]: ls -l /tmp/tmp*
ls: /tmp/tmp*: No such file or directory
From the docstring, it gets automatically deleted on close:
def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix="",
prefix=template, dir=None):
"""Create and return a temporary file.
Arguments:
'prefix', 'suffix', 'dir' -- as for mkstemp.
'mode' -- the mode argument to os.fdopen (default "w+b").
'bufsize' -- the buffer size argument to os.fdopen (default -1).
The file is created as mkstemp() would do it.
Returns an object with a file-like interface; the name of the file
is accessible as file.name. The file will be automatically deleted
when it is closed.
"""
HTH,
- jmj
More information about the Python-list
mailing list