Python - tempfile.TemporaryFile cannot be read; why?

Sridhar Ratnakumar picture Sridhar Ratnakumar · Jul 29, 2009 · Viewed 14.9k times · Source

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)

Answer

ramosg picture ramosg · Jul 29, 2009

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.