Search code examples
pythonpandasexport-to-csv

Write comments in CSV file with pandas


I would like to write some comments in my CSV file created with pandas. I haven't found any option for this in DataFrame.to_csv (even though read_csv can skip comments) neither in the standard csv module. I can open the file, write the comments (line starting with #) and then pass it to to_csv. Does any body have a better option?


Solution

  • df.to_csv accepts a file object. So you can open a file in a mode, write you comments and pass it to the dataframe to_csv function.

    For example:

    In [36]: df = pd.DataFrame({'a':[1,2,3], 'b':[1,2,3]})
    
    In [37]: f = open('foo', 'a')
    
    In [38]: f.write('# My awesome comment\n')
    
    In [39]: f.write('# Here is another one\n')
    
    In [40]: df.to_csv(f)
    
    In [41]: f.close()
    
    In [42]: more foo
    # My awesome comment
    # Here is another one
    ,a,b
    0,1,1
    1,2,2
    2,3,3