如何将CSV文件转换为行列表?

2024-04-20 13:26:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前有一个CSV文件保存为Windows逗号分隔值

^{1}$

退货

^{pr2}$

我试着一列一列地列一个清单

f = open('file.csv')
csv_f = csv.reader(f)
for row in f:
    print row[2]
f.close()

我只收到第三封信:mes和{}。在

在Mac上用Python编写


Tags: 文件csvinforclosewindowsopenreader
3条回答

你想要for row in csv_f: …,而不是{}。在

作为处理csv文件的正确方法,可以使用csv模块:

>>> import csv
>>> with open('f_name.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=',')
...     for row in spamreader:
...         print baseUrl + ' '.join(row)

这将以列表的形式给出行。如果你想把它们都列在一个列表中,只需:

^{pr2}$

注意,spamreader是一个迭代器,可以通过list()函数将其转换为list。在

您还可以通过将spamreader传递给zip函数来获得列列表:

>>> import csv
>>> with open('f_name.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=',')
...     print zip(*spamreader)

此函数读取CSV并将其作为列表返回

def csv2list(csvFile):
    outList = list()
    reader = csv.reader(open(csvFile))
    for row in reader:
        outList.append(row)            
    return outList

使用示例:

^{pr2}$

相关问题 更多 >