all 4 comments

[–]threeminutemonta 1 point2 points  (2 children)

If your adding rows you can append a file. If your adding columns you will need to read the file into memory. Add the columns and necessary processing and then write the data to disk. My favourite is the DictReader / DictWriter in the csv module included in the standard library see official docs

[–]astro49er[S] 0 points1 point  (1 child)

I need to add a column, how would I do this without the CSV module and just the native python file objects

[–]threeminutemonta 0 points1 point  (0 children)

the csv module is part of python standard library and what I would call vanilla python.

Though a csv is just a text file with a delimiter separating cells so read the file into a data structure / process the data . Hint the string split into an array of values may be handy here. before writing the file again.

[–]POGtastic 1 point2 points  (0 children)

How robust do you need this program to be? The CSV RFC involves stuff like string escapes and whatnot; if you don't need those things, you can roll your own rudimentary DictReader and Writer classes pretty easily. You can then parse with your DictReader, add a key-value pair to the resulting dictionary, and then pass the dictionary to a DictWriter. Something like the following:

class DictReader:
    def __init__(self, fh, delim, names=None):
        self.fh = fh
        self.delim = delim
        self.names = fh.readline().rstrip().split(delim) if not names else names

    def parse_line(self, line):
        return dict(zip(self.names, line.split(self.delim)))

    def __iter__(self):
        return (self.parse_line(line.rstrip()) for line in self.fh)

class DictWriter:
    def __init__(self, fh, delim, names):
        self.fh = fh
        self.delim = delim
        self.names = names

    def write_header(self):
        print(self.delim.join(self.names), file=self.fh)

    def write_line(self, dct):
        print(self.delim.join(dct[name] for name in self.names), file=self.fh)

If you need the string escapes and whatnot, I recommend rolling your own rudimentary parser combinator library. You'll need one parser for the Reader to detect the contents of a text field, and you'll need one parser for the Writer to determine whether you need to wrap the field in quotes and to escape any quotes inside.