سؤال

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'
هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

You could use tempfile.mkstemp(). From the documentation:

Creates a temporary file in the most secure manner possible. There are no race conditions in the file’s creation, assuming that the platform properly implements the os.O_EXCL flag for os.open(). The file is readable and writable only by the creating user ID. If the platform uses permission bits to indicate whether a file is executable, the file is executable by no one. The file descriptor is not inherited by child processes.

Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.

You can then use the open() builtin function to create and open that file several times. Remember to delete the file when you are done, as this is not done automatically.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top