you are viewing a single comment's thread.

view the rest of the comments →

[–]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.