简体   繁体   中英

Summing values in multiple lines separated by comma from text file in Python

I want to add values from each line separated by comma. For example , If my input file contents are:

1,2,3
4,5,6

The output should be:

6
15

Here is my code:

with open('untitled6.txt', 'r') as istr:
    for line in istr:
        sum(map(int,open('untitled6.txt').readline().split(',')))

The output should be written in a new file like this:

6
15 

Code

with open('untitled6.txt', 'r') as istr:
    for line in istr:
        print(sum([int(v) for v in line.split(',')]))

Output

6
15

You don't need to open the file twice, use the lines you extract from istr :

with open('untitled6.txt', 'r') as istr:
    for line in istr:
        print(sum(map(int, line.split(','))))

Outputs:

6
15

You may also consider using the csv package to read the file:

import csv                                                                      

with open('test.csv', 'r', newline='') as istr:                                 
    reader = csv.reader(istr)                                                   
    for line in reader:                                                         
        print(sum(map(int, line)))

It seems you have a couple of problems:

  • you open the file once, but you do not really use it
  • you never print() the result of the sum() .

Fixing these would make your code work:

with open('untitled6.txt', 'r') as istr:
    for line in istr:
        print(sum(map(int, line.split(','))))
with open('untitled6.txt', 'r') as istr:
    for line in istr:
        total = 0
        listL = line.split(",")
        for i in listL:
            total = total + int(i)
        print(total)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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