Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV write to file starting with comment lines

I need to create a file that contains csv data (or tsv, rather) prepended by several commented (via "#") lines (processing instructions for a third party program).

What I have tried was to open a template file with comments in append mode and write csvrows to it:

...
with open('template.txt', 'a+') as csvfile:
        for record in records:
            csvWriter = csv.writer(csvfile, delimiter='\t',quotechar='"', quoting=csv.QUOTE_MINIMAL)
            csvWriter.writerow([record['Id'], record['Email']])
....    

This does not work (no matter which flags I use to open the file). It does not overwrite the commented lines, but it skips as many csv rows as there are comments.

So this is apparently not how to do it. So what would be the proper way in Python (2.7) to create a file that mixes non-csv data and csv data (I want my csv fields properly quoted etc, so I do not want to use a simple write operation for my csv rows) ?

like image 834
Eike Pierstorff Avatar asked Oct 19 '25 08:10

Eike Pierstorff


1 Answers

You don't have to create a new csv.writer every iteration, it is just a wrapper around file.write.

import csv
with open("template.txt", "wt") as fp:

    fp.write("# first commented line\n")
    fp.write("# second commented line\n")

    writer = csv.writer(fp)

    for record in records:
        writer.writerow([record["Id"], record["Email"]])

    fp.write("# a commented line among the records\n")

    for record in more_records:
        writer.writerow([record["Id"], record["Email"]])
like image 79
pgy Avatar answered Oct 21 '25 21:10

pgy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!