views:

900

answers:

2

The official documentation for TemporaryFile reads:

The mode parameter defaults to 'w+b' so that the file created can be read and written without being closed.

Yet, the below code does not work as expected:

import tempfile

def play_with_fd():
    with tempfile.TemporaryFile() as f:
        f.write('test data\n')
        f.write('most test data\n')

        print 'READ:', f.read()

        f.write('further data')

        print 'READ:', f.read()

        f.write('even more')
        print 'READ:', f.read()

        print 'READ:', f.read()
        print 'READ:', f.read()

if __name__ == '__main__':
    play_with_fd()

The output I get is:

> python play.py 
READ: 
READ: 
READ: 
READ: 
READ:

Can anyone explain this behavior? Is there a way to read from temporary files at all? (without having to use the low-level mkstemp that wouldn't automatically delete the files; and I don't care about named files)

+5  A: 

read() does not return anything because you are at the end of the file. You need to call seek() first before read() will return anything. For example, put this line in front of the first read():

f.seek(-10, 1)

Of course, before writing again, be sure to seek() to the end (if that is where you want to continue writing to).

Heikki Toivonen
+3  A: 

You must put

f.seek(0)

before trying to read the file (this will send you to the beginning of the file), and

f.seek(0, 2)

to return to the end so you can assure you won't overwrite it.

willehr
Instead of `f.seek(0, 2)` I'd use `f.seek(0, os.SEEK_END)`
Sridhar Ratnakumar