在 Python 中从 CSV 文件中读取行 [英] Reading rows from a CSV file in Python

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

问题描述

我有一个 CSV 文件,下面是它的示例:

I have a CSV file, here is a sample of what it looks like:

Year:  Dec: Jan:
1      50   60
2      25   50
3      30   30
4      40   20
5      10   10

我知道如何读取文件并打印每一列(例如 - ['Year', '1', '2', '3', etc]).但我真正想做的是读取行,就像这样 ['Year', 'Dec', 'Jan'] 然后 ['1', '50', '60'] 等.

I know how to read the file in and print each column (for ex. - ['Year', '1', '2', '3', etc]). But what I actually want to do is read the rows, which would be like this ['Year', 'Dec', 'Jan'] and then ['1', '50', '60'] and so on.

然后我想将这些数字 ['1', '50', '60'] 存储到变量中,以便我以后可以对它们进行总计,例如:

And then I would like to store those numbers ['1', '50', '60'] into variables so I can total them later for ex.:

Year_1 = ['50', '60'].然后我可以做sum(Year_1) = 110.

我将如何在 Python 3 中做到这一点?

How would I go about doing that in Python 3?

推荐答案

你可以这样做:

with open("data1.txt") as f:
    lis = [line.split() for line in f]        # create a list of lists
    for i, x in enumerate(lis):              #print the list items 
        print "line{0} = {1}".format(i, x)

# output 
line0 = ['Year:', 'Dec:', 'Jan:']
line1 = ['1', '50', '60']
line2 = ['2', '25', '50']
line3 = ['3', '30', '30']
line4 = ['4', '40', '20']
line5 = ['5', '10', '10']

或:

with open("data1.txt") as f:
    for i, line in enumerate(f):             
        print "line {0} = {1}".format(i, line.split())

# output         
line 0 = ['Year:', 'Dec:', 'Jan:']
line 1 = ['1', '50', '60']
line 2 = ['2', '25', '50']
line 3 = ['3', '30', '30']
line 4 = ['4', '40', '20']
line 5 = ['5', '10', '10']

with open('data1.txt') as f:
    print "{0}".format(f.readline().split())
    for x in f:
        x = x.split()
        print "{0} = {1}".format(x[0],sum(map(int, x[1:])))

# output          
['Year:', 'Dec:', 'Jan:']
1 = 110
2 = 75
3 = 60
4 = 60
5 = 20

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

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