I am new to python2.6 programming,my goal is to create .txt or .xls "temporary file" in temp directory of os and write some data to it.and then read the data from "temporary file", after completion of reading data,remove "temporary file" from temp directory.
for that process i choose NamedTemporaryFile(),but can't achieved. Could you suggest how can i achieve it.Thanks in advance.
>>> import os
>>> import tempfile
>>> with tempfile.NamedTemporaryFile() as temp:
print temp.name
temp.write('Some data')
f = open(os.path.join(tempfile.gettempdir(),temp.name))
lines = f.readlines()
f.close()
temp.flush()
c:\users\110\appdata\local\temp\tmpf8p3kc
Traceback (most recent call last):
File "<pyshell#3>", line 4, in <module>
f = open(os.path.join(tempfile.gettempdir(),temp.name))
IOError: [Errno 13] Permission denied: 'c:\\users\\110\\appdata\\local\\temp\\tmpf8p3kc'
Source code: Lib/tempfile.py. This module creates temporary files and directories. It works on all supported platforms. TemporaryFile , NamedTemporaryFile , TemporaryDirectory , and SpooledTemporaryFile are high-level interfaces which provide automatic cleanup and can be used as context managers.
gettempdir() This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp. This directory is used as default value of dir parameter.
The approach I've used is to use file = tempfile.NamedTemporaryFile(..., delete=False)
, to close the resulting file after I'm done writing to it, and to manually call os.remove(file.name)
when I'm done. (You can do the file removal in the __exit__
method of a custom context manager to make this nicer to use with with
.)
I've had this problem once..
From the documentation: "Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later)."
Why don't you just try to read from the file using the temp
object when it's still open? If it's open with w+b
mode then you should be able to seek() and read()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With