Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i read NamedTemporaryFile in python.?

Tags:

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'
like image 777
user1559873 Avatar asked Sep 19 '13 19:09

user1559873


People also ask

What is Tempfile NamedTemporaryFile ()?

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.

Where is my Python TEMP folder?

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.


2 Answers

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

like image 135
jamesdlin Avatar answered Oct 21 '22 04:10

jamesdlin


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

like image 44
Ofir Israel Avatar answered Oct 21 '22 03:10

Ofir Israel