简体   繁体   中英

Python csv.writer - is it possible to write to a variable?

Is it possible to use csv.writer to write data to a variable rather than a file?

I was hoping I could do something like this:

data = ''
csv.writer(data)
# ...... (I have removed the csv processing code for brevity)
message = EmailMessage('Invoice for 2012', 'h', 'noreply@test.co.uk', ['test@test.co.uk'])
message.attach('invoice.csv', data, 'text/csv')
message.send()

When I execute the code I get the following error:

   argument 1 must have a "write" method

The csv.writer class needs a file-like object, something with a .write() method. A StringIO class would be best here:

from cStringIO import StringIO

data = StringIO()
csv.writer(data)
# write your stuff
message = EmailMessage('Invoice for 2012', 'h', 'noreply@test.co.uk', ['test@test.co.uk'])
message.attach('invoice.csv', data.getvalue(), 'text/csv')
message.send()

I used the C-variant of the StringIO module there; the advantage is speed, the disadvantage that you can use each instance only as a writable or a readable file. Since all you do is write to it before retrieving the written data, that's just fine.

You can always use StringIO whenever you need a file-like object (with a write method) and do not want to create an actual file in the filesystem.

An advantage of this memory-file approach is that I/O is much faster than with a real storage backend. If you want to be even faster, you can use cStringIO . Note that cStringIO is not always available, so you could do something like

try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM