Python-从csv文件读取特定列 [英] Python - Reading Specific column from csv file

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

问题描述

我只想读取csv文件中的第一列.我尝试了下面的代码,但没有从可用的解决方案中得到结果.

I want to read only first column from csv file. I tried the below code but didn't got the result from available solution.

data = open('data.csv')
reader = csv.reader(data)
interestingrows = [i[1] for i in reader]'

我得到的错误是:

Traceback (most recent call last):
    File "G:/Setups/Python/pnn-3.py", line 12, in <module>
         interestingrows = [i[1] for i in reader]
    File "G:/Setups/Python/pnn-3.py", line 12, in <listcomp>
         interestingrows = [i[1] for i in reader]
IndexError: list index out of range

推荐答案

您还可以使用 DictReader 通过标题访问列

You can also use DictReader to access columns by their header

例如:如果您有一个带有标题("Oopsy","Daisy","Rough"和"Tumble")的名为"stackoverflow.csv"的文件 您可以使用此脚本访问第一列:

For example: If you had a file called "stackoverflow.csv" with the headers ("Oopsy", "Daisy", "Rough", and "Tumble") You could access the first column with this script:

import csv
with open(stackoverflow.csv) as csvFile:
#Works if the file is in the same folder, 
# Otherwise include the full path
    reader = csv.DictReader(csvFile)
    for row in reader:
        print(row["Oopsy"])

这篇关于Python-从csv文件读取特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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