Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python tempfile: how to open several times the temp file?

I am trying to use the tempfile module. (http://docs.python.org/2.7/library/tempfile.html) I am looking for a temporary file that I could open several times to get several streams to read it.

tmp = ...
stream1 = # get a stream for the temp file
stream2 = # get another stream for the temp file

I have tried several functions (TemporaryFile, NamedTemporaryFile, SpooledTemporaryFile) and using the fileno method or so but I could not perform what I am looking for.

Any idea of should I just make my own class?

Thanks

> UPDATE

I get an error trying to open the file with its name...

In [2]: t = tempfile.NamedTemporaryFile()
In [3]: t.write('abcdef'*1000000)
In [4]: t.name
Out[4]: 'c:\\users\\mike\\appdata\\local\\temp\\tmpczggbt'
In [5]: f = open(t.name)
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-6-03b9332531d2> in <module>()
----> 1 f = open(t.name)

IOError: [Errno 13] Permission denied: 'c:\\users\\mike\\appdata\\local\\temp\\tmpczggbt'
like image 585
Michael Avatar asked Jul 06 '13 11:07

Michael


People also ask

How do I create a temporary csv file in Python?

Creating a Temporary FileThe file is created using the TemporaryFile() function. By default, the file is opened in w+b mode, that is, we can both read and write to the open file. Binary mode is used so that files can work with all types of data. This file may not have a proper visible name in the file system.

What is Tempfile Mkdtemp ()?

tempfile. mkdtemp (suffix=None, prefix=None, dir=None) Creates a temporary directory in the most secure manner possible. There are no race conditions in the directory's creation. The directory is readable, writable, and searchable only by the creating user ID.

What is used to store temporary data in Python?

tempfile comes in handy whenever you want to use temporary files to store data in a Python program.


1 Answers

File objects (be they temporary or otherwise) cannot be read multiple times without re-positioning the file position back to the start.

Your options are:

  • To reopen the file multiple times, creating multiple file objects for the same file.
  • To rewind the file object before each read.

To reopen the file, use a NamedTemporaryFile and use a regular open() call to re-open the same filename several times. You probably will want to pass delete=False to the constructor, especially on Windows, to be able to do this.

To rewind, call .seek(0) on the file object.

like image 120
Martijn Pieters Avatar answered Nov 14 '22 23:11

Martijn Pieters