“CSV”是不是一个标准,即使“CSV”的字面意思是“逗号分隔值”,使用标签作为分隔符只是像逗号一样常见,如果不是更常见的话。另请参见维基百科:http://en.wikipedia.org/wiki/Comma-separated_values
为了处理包含分隔符(即制表符或逗号)的CSV字段,通常引用数据,即使用双引号。没有标准 - 有时只引用包含分隔符的数据字段。在下面的例子中,所有的字段都会被引用。
使用csv内置库,可以非常容易地根据需要修改输出CSV文件的格式。
import csv
objs = [{'name': 'knut', 'age': 74, 'count': 13},
{'name': 'lydia', 'age': 14, 'count': 3}]
with open("/tmp/example.csv", "w") as outfile:
## Ordering of the fields in the CSV output
headers = ['name', 'age', 'count']
## although "CSV" stands for "comma separated values",
## it's quite common to use other delimiters i.e. TAB
## and still call it "CSV".
writer = csv.writer(outfile, delimiter="\t", quotechar='"', quoting=csv.QUOTE_ALL)
## it's common in CSV to have the headers on the first line
writer.writerow(headers)
## Write out the data
for obj in objs:
writer.writerow([obj[key] for key in headers])
这个例子也说明了在Python浓缩列表操作... [obj[key] for key in headers]
的意思是“给我的obj [关键]列表中所有标题密钥”。
http://docs.python.org/library/csv.html – tobixen 2012-07-09 14:07:59