Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading