简体   繁体   English

获取第一列CSV文件Python

[英]getting first column CSV file Python

Trying to get first column (names) into a list to show the user and is then updated with the changes to CSV file. 尝试使第一列(名称)进入列表以显示用户,然后使用对CSV文件的更改进行更新。 Using this code: 使用此代码:

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

However, i get the underired output of: 但是,我得到了下面的输出:

['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']

You are appending the empty column list every other row; 您将每隔一行追加一个空column列表。 test for the column before appending: 追加之前测试列:

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

Do not use an endless loop ( while True: ) in there. 请勿在其中使用无限循环( while True: )。

Or using a list comprehension and the file as a context manager to close it automatically: 或者使用列表推导和文件作为上下文管理器来自动关闭它:

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

Note that I added the newline='' argument to the open() call; 请注意,我在open()调用中添加了newline=''参数; this is recommended for CSV files because they can use a mix of line endings between values and rows, which the csv.reader() will manage for you if you let it. 推荐使用CSV文件,因为它们可以在值和行之间混合使用行尾,如果您愿意, csv.reader()将为您管理。

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

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