CSV with comments

skip at pobox.com skip at pobox.com
Tue Jul 18 15:34:28 EDT 2006


    >> In csv.reader, is there any way of skip lines that start whith '#' or
    >> empty lines

Nope.  When we wrote the module we weren't aware of any "spec" that
specified comments or blank lines.  You can easily write a file wrapper to
filter them out though:

    class BlankCommentCSVFile:
        def __init__(self, fp):
            self.fp = fp

        def __iter__(self):
            return self

        def next(self):
            line = self.fp.next()
            if not line.strip() or line[0] == "#":
                return self.next()
            return line

Use it like so:

    reader = csv.reader(BlankCommentCSVFile(open("somefile.csv")))
    for row in reader:
        print row

Skip



More information about the Python-list mailing list