我有一个example.csv包含内容的文件
example.csv
1,"A towel,",1.0 42," it says, ",2.0 1337,is about the most ,-1 0,massively useful thing ,123 -2,an interstellar hitchhiker can have.,3
如何example.csv使用Python 阅读?
同样,如果我有
data = [(1, "A towel,", 1.0), (42, " it says, ", 2.0), (1337, "is about the most ", -1), (0, "massively useful thing ", 123), (-2, "an interstellar hitchhiker can have.", 3)]
如何data使用Python 写入CSV文件?
以下是一些最小的完整示例,这些示例如何读取CSV文件以及如何使用Python编写CSV文件。
Python 2 + 3:读取CSV文件
Python
# -*- coding: utf-8 -*- import csv import sys # Define data data = [(1, "A towel,", 1.0), (42, " it says, ", 2.0), (1337, "is about the most ", -1), (0, "massively useful thing ", 123), (-2, "an interstellar hitchhiker can have.", 3)] # Write CSV file kwargs = {'newline': ''} mode = 'w' if sys.version_info < (3, 0): kwargs.pop('newline', None) mode = 'wb' with open('test.csv', mode, **kwargs) as fp: writer = csv.writer(fp, delimiter=',') # writer.writerow(["your", "header", "foo"]) # write header writer.writerows(data) # Read CSV file kwargs = {'newline': ''} mode = 'r' if sys.version_info < (3, 0): kwargs.pop('newline', None) mode = 'rb' with open('test.csv', mode, **kwargs) as fp: reader = csv.reader(fp, delimiter=',', quotechar='"') # next(reader, None) # skip the headers data_read = [row for row in reader] print(data_read)
之后,的内容data_read是
[['1', 'A towel,', '1.0'], ['42', ' it says, ', '2.0'], ['1337', 'is about the most ', '-1'], ['0', 'massively useful thing ', '123'], ['-2', 'an interstellar hitchhiker can have.', '3']]
Unicode和Python 2.X
如果要编写Unicode,则必须安装unicodecsv。千万不能用打开文件codecs.open,而只是用open。用写
import unicodecsv as csv # Write CSV file with open('test.csv', 'w', newline='') as fp: writer = csv.writer(fp, encoding='utf-8') # writer.writerow(["your", "header", "foo"]) # write header writer.writerows(data)