如何将配置行位于标头之前的 Dataframe 写入csv

lrpiutwd  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(119)

我使用pyhton脚本来管理采集系统中的不同日志文件,boards ecc。我正在构建一个大的dataframe,它是其他dfs的合并,最后我将其放入csv文件,在最后一行下面:

dF_COMP.to_csv(path1 + nomefile, sep=';', decimal= ',' , columns=columns)

我想在csv的第一行添加一行配置参数。
我可以用dataframe构建csv,然后再次打开它,然后添加该行,但我认为这不是最好的主意,因为我希望构建更大的文件......有更好的主意吗?

wxclj1h5

wxclj1h51#

我可以用 Dataframe 构建csv,然后再次打开它,然后添加该行,但我认为这不是最好的主意,因为我希望构建甚至大文件...
反其道而行之:

with open(path1 + nomefile, 'w') as csvfile:
    csvfile.write(f'# Config blah blah\n')  # note the '#' as comment character
    df.to_csv(csvfile, sep=';', decimal= ',', columns=columns)

使用pd.read_csv再次读取文件:

pd.read_csv(path1 + nomefile, comment='#')  # to skip lines begin with '#'

# OR

pd.read_csv(path1 + nomefile, skiprows=1)  # to skip the first line

相关问题