如何在标题之前写入包含配置行的数据框到 CSV 文件中

huangapple go评论75阅读模式
英文:

How to write to csv a dataframe with config line before headers

问题

I want to add in the first line of the csv a row with configuration parameters.

我想在CSV文件的第一行添加一个包含配置参数的行。

I can build the csv with the dataframe, then open it again and then add the line but I think is not the best idea as I expect to build even big files...

我可以使用DataFrame构建CSV文件,然后再次打开它并添加行,但我认为这不是最好的方法,因为我预计会构建非常大的文件...

Any better idea?

有更好的方法吗?

英文:

I'm using a pyhton script to manage different logfiles from an acquisition system, boards ecc.
I'm building a big dataframe which is the merge of other dfs and at the end i'm putting it to a csv file, below last line:

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

I want to add in the first line of the csv a row with configuration parameters.

I can build the csv with the dataframe, then open it again and then add the line but I think is not the best idea as I expect to build even big files...
Any better idea?

答案1

得分: 2

我可以构建包含数据框的CSV文件,然后重新打开它,然后添加一行,但我认为这不是最好的主意,因为我希望能够处理更大的文件...

执行相反的操作:

with open(path1 + nomefile, 'w') as csvfile:
    csvfile.write('# Config blah blah\n')  # 注意'#'作为注释字符
    df.to_csv(csvfile, sep=';', decimal=',', columns=columns)

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

pd.read_csv(path1 + nomefile, comment='#')  # 跳过以'#'开头的行

# 或者

pd.read_csv(path1 + nomefile, skiprows=1)  # 跳过第一行
英文:

> I can build the csv with the dataframe, then open it again and then add the line but I think is not the best idea as I expect to build even big files...

Do the opposite:

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)

To read the file again with 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

huangapple
  • 本文由 发表于 2023年3月31日 20:39:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75898635.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定