简体   繁体   中英

How can i read NamedTemporaryFile in python.?

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'

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()

I've created an alternate mechanism which creates a named temporary file but does not keep it open. It is thus completely useable anywhere. Instead of deleting on close it deletes at the end of the with block.

Install the shelljob pip package. Example usage from the docs :

with fs.NamedTempFile() as nm:
    proc.call( "curl http://mortoray.com/ -o {}".format( nm ) )
    html = open(nm).read()
    print( len(html) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM