简体   繁体   English

第一次写入CSV文件后跳过标题(Python)

[英]Skip header after the first time CSV file is written into (Python)

The following script for writing to a CSV file is going to run on a server which will automate the run. 用于写入CSV文件的以下脚本将在将自动运行的服务器上运行。

    d = {'col1': a, col2': b, col3': c,}
    df = pandas.DataFrame(d, index = [0])
    with open('foo.csv', 'a') as f:
            df.to_csv(f, index = False)    

The problem is, everytime I run it, the header gets copied to the CSV file. 问题是,每次运行它时,标头都会被复制到CSV文件中。 How can I modify this code to have the header copied to the CSV file only the first time its run, and never after that? 如何修改此代码,以便仅在第一次运行时将标头复制到CSV文件,从此之后永远不会?

Any help will be appreciated :) 任何帮助将不胜感激 :)

try this: 试试这个:

filename = '/path/to/file.csv'
df.to_csv(filename, index=False, mode='a', header=(not os.path.exists(filename)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM