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()
''
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With