Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: TemporaryFile returns empty string when read

Tags:

python

django

I need to create a file from a string so I can use it as an attachment for an email in Django. After some Googling I found the tempfile module with TemporaryFile but it's not working as I expect.

the following code returns an empty string.

>>> f = tempfile.TemporaryFile()
>>> f.write('foobar')
>>> f.read()
''
like image 688
Pickels Avatar asked Dec 21 '22 16:12

Pickels


1 Answers

When you call read, it is trying to read from where it left off, which is at the end of the file. You need to jump to the beginning of the file before you read it:

f.seek(0)
f.read()

If you need to write again, you should jump to the end before writing if you don't want to overwrite your stuff:

f.seek(0, os.SEEK_END)
f.write('some stuff')
like image 150
Spike Avatar answered Jan 06 '23 17:01

Spike