gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 02:28:02 24 4
gpt4 key购买 nike

以下用于写入 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)

问题是,每次我运行它时,标题都会被复制到 CSV 文件中。我如何修改此代码以仅在第一次运行时将 header 复制到 CSV 文件,之后再不复制?

任何帮助将不胜感激:)

最佳答案

试试这个:

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

关于python - 第一次写入 CSV 文件后跳过标题(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38361582/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com