Reading rows from a CSV file in Python

前端 未结 10 2435
慢半拍i
慢半拍i 2020-11-30 23:58

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
         


        
10条回答
  •  盖世英雄少女心
    2020-12-01 00:28

    You could do something like this:

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

    or :

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

    Edit:

    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
    

提交回复
热议问题