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
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'
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.
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.
tempfile comes in handy whenever you want to use temporary files to store data in a Python program.
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, 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.
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