英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论