Python: tempfile read

Before reading tempfile contents, execute “seek(0)” is needed to point beginning of the file.

http://stackoverflow.com/questions/1202848/python-tempfile-temporaryfile-cannot-be-read-why

# -*- coding:utf-8 -*-
from tempfile import NamedTemporaryFile
from os import SEEK_END


with NamedTemporaryFile() as f:
    #before seek(0) f.read() returns nothing
    f.write('Foo')
    print f.read()
    >>
    # after seeking we can read the contents
    f.seek(0)
    print f.read()
    >>Foo
    # by seek(0, os.SEEK_END) file pointer moves to end of the file
    f.seek(0, SEEK_END)
    f.write('Bar')
    f.seek(0)
    print f.read()
    >>FooBar

 

Leave a Reply

Your email address will not be published. Required fields are marked *