获得第一列CSV文件Python

时间:2014-04-10 16:51:49

标签: python csv python-3.x

尝试将第一列(名称)放入列表中以显示用户,然后使用对CSV文件的更改进行更新。 使用此代码:

import csv
list = []
exRtFile = open ('exchangeRate.csv','r')
exchReader = csv.reader(exRtFile)
while True:
    for column in exchReader:
        list.append(column and column[0])
        print(list)
        exRtFile.close

然而,我获得了未经编辑的输出:

['US Dollar']
['US Dollar', []]
['US Dollar', [], 'Japanese Yen']
['US Dollar', [], 'Japanese Yen', []]
['US Dollar', [], 'Japanese Yen', [], 'Euro']
['US Dollar', [], 'Japanese Yen', [], 'Euro', []]
['US Dollar', [], 'Japanese Yen', [], 'Euro', [], 'Pound Sterling']
['US Dollar', [], 'Japanese Yen', [], 'Euro', [], 'Pound Sterling', []]
['US Dollar', [], 'Japanese Yen', [], 'Euro', [], 'Pound Sterling', [], 'Japanese Yen']

1 个答案:

答案 0 :(得分:3)

您每隔一行追加空column列表;在追加之前测试列:

col = []
exRtFile = open ('exchangeRate.csv','r')
exchReader = csv.reader(exRtFile)
for column in exchReader:
    if column:
        col.append(column[0])

在那里使用无限循环(while True:)。

或者使用列表推导和文件作为上下文管理器来自动关闭它:

with open('exchangeRate.csv', newline='') as exRtFile:
    exchReader = csv.reader(exRtFile)
    col = [c[0] for c in exchReader if c]

请注意,我在newline=''电话中添加了open()参数;这建议用于CSV文件,因为它们可以在值和行之间使用混合的行结尾,如果您允许,csv.reader()将为您管理。