获取第一列CSV文件Python [英] getting first column CSV file Python

查看:103
本文介绍了获取第一列CSV文件Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to get first column (names) into a list to show the user and is then updated with the changes to CSV file. 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; 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.

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

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]

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

Note that I added the newline='' argument to the open() call; 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文件Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆