Home > Net >  sum rows of numbers to CSV file and add a column to add numbers to row and save to same file
sum rows of numbers to CSV file and add a column to add numbers to row and save to same file

Time:07-02

For example, I want to add the same csv file below the lines and add them at the end of the line:

   3, 3, 1, 1, 1, 1, 1
   1, 1, 4, 5, 6, 7, 8
   1, 5, 6, 7, 4, 3, 1

The sample output is similar to the following:

3, 3, 1, 1, 1, 1, 1, 11
1, 1, 4, 5, 6, 7, 8, 32
1, 5, 6, 7, 4, 3, 1, 27

You see that at the end is the sum of the line numbers and I want to save it in the same file. The problem I have:

import re
def process(path):
    f = open(path, 'r ')
    line = f.readlines()
    sumnum = 0
    for i in line:
        listnum = re.findall('-?\d ', i)
        for j in listnum:
            sumnum  = int(j)
        i = i.rstrip()   ', '
        f.write(i   str(sumnum)   '\n')
        sumnum = 0
    f.close()

But the output is as follows

3, 3, 1, 1, 1, 1, 1
1, 1, 4, 5, 6, 7, 8
1, 5, 6, 7, 4, 3, 13, 3, 1, 1, 1, 1, 1, 11
1, 1, 4, 5, 6, 7, 8, 32
1, 5, 6, 7, 4, 3, 1, 27

How to write code that did not have this problem?

CodePudding user response:

If you don't want to use the CSV library, you can use the following method:

def csv_reader(path):
    with open(path) as csv:
        for row in csv.readlines():
            yield row.rstrip()

def process(path):
    with open('ans.csv', 'w') as out:
        for line in csv_reader(path):
            ssum = sum(list(map(int, line.split(','))))
            line = line   ','   str(ssum)
            out.write(line   '\n')  

output in ans.csv:

3, 3, 1, 1, 1, 1, 1, 11
1, 1, 4, 5, 6, 7, 8, 32
1, 5, 6, 7, 4, 3, 1, 27

CSV library smaple:

import csv
def process(path):
    with open(path, 'r') as f:
        reader = csv.reader(f)
        with open('ans.csv', 'w', newline='') as f1:
            writer = csv.writer(f1)
            for row in reader:
                y = []
                x = row
                for i in map(int, x):
                    y.append(i)
                #print(y)
                y.append(sum(y))
                writer.writerow(y)
  • Related