I need to creat开发者_运维问答e 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')
Try doing an f.seek(0)
to rewind to the beginning between the write and read. A read()
call always leaves the “file pointer” (which is kind of the operating system's index finger, pointing to remember where in the file you are currently at) at the end of the data you have just written.
if you have a string already in memory, you can use StringIO or cStringIO to simulate file over string. This should be much faster as there will be no disk operations at all.
精彩评论