0

I'm trying to append a .csv file with monthly numbers using python. The .csv looks like something like this:

Month,Jan,Feb
Total,70,80
Critical,20,30
High,50,50

I've been trying to develop a method along these lines with no luck:

def append_csv(high_value, critical_value)

That would have result in the following:

append_csv(30, 20)

Output:

Month,Jan,Feb,Mar
Total,70,80,50
Critical,20,30,20
High,50,50,30

I have looked at Appending to the end of a certain line, however it felt inefficient for what I was trying to accomplish and wouldn't modify row one. Thank you for your help.

Community
  • 1
  • 1
mpace
  • 93
  • 1
  • 6
  • 3
    It would make more sense, and be easier, to write `Month,High,Critical,Total`, and then append a line for each month: `Jan,20,50,70`, `Feb,30,50,80`, etc. – Mark Tolonen Jan 28 '16 at 05:36
  • Easier to write for, but this data is represented visually through a graph that represents values over time. – mpace Jan 28 '16 at 05:46
  • 2
    But its easy to turn the columns of a proper csv file into a graph. You are still better off with @MarkTolonen's suggestion. – tdelaney Jan 28 '16 at 05:49
  • The csv is used by a proprietary dashboard. This is the format it uses. I would love to change it but it has already been well established how data is presented – mpace Jan 28 '16 at 05:55
  • 1
    Append one row vs. rewrite the entire file to add a column. Bad design. – Mark Tolonen Jan 28 '16 at 07:30

1 Answers1

0

If you want to append data to lines of a file, the remaining lines have to be copied further down the file to make room for the larger line. By writing a new file and then renaming it at the end you hold less data in memory at any given time. The linked answer is overkill for what you want... since you only want to append data, you don't need the csv module to carve out rows from the existing file.

This script assumes you only want to add a single set of data to the file.

import os

def append_data(filename, month, total, critical, high):
    vals = month, total, critical, high
    tmp_filename = filename + '.tmp'
    if os.path.exists(tmp_filename):
        os.remove(tmp_filename)
    with open(filename) as fin, open(tmp_filename, 'w') as fout:
         for val in vals:
             col = ',{}\n'.format(val)
             fout.write(next(fin)[:-1] + col)
    os.remove(filename)
    os.rename(tmp_filename, filename)

# test

with open('deleteme', 'w') as fp:
    fp.write("""Month,Jan,Feb
Total,70,80
Critical,20,30
High,50,50
""")

append_data('deleteme', 'Mar', 50, 20, 30)

print(open('deleteme').read())
tdelaney
  • 73,364
  • 6
  • 83
  • 116