简体   繁体   English

Python csv.writer - 是否可以写入变量?

[英]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? 是否可以使用csv.writer将数据写入变量而不是文件?

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. csv.writer类需要一个类文件对象,使用.write()方法。 A StringIO class would be best here: StringIO在这里最好:

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; 我在那里使用了StringIO模块的C变体; 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. 每当需要类似文件的对象(使用write方法)并且不想在文件系统中创建实际文件时,您始终可以使用StringIO

An advantage of this memory-file approach is that I/O is much faster than with a real storage backend. 这种内存文件方法的一个优点是I / O比实际存储后端快得多。 If you want to be even faster, you can use cStringIO . 如果你想更快,你可以使用cStringIO Note that cStringIO is not always available, so you could do something like 请注意, cStringIO并不总是可用,因此您可以执行类似的操作

try:
    import cStringIO as StringIO
except ImportError:
    import StringIO

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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