python - 蟒蛇 | 如何在创建 csv 文件时向其添加标题?
问题描述
我正在解析从管道获取的十六进制数据。数据被逐行解析并写入 csv 文件。我需要添加标题。于是得到的数据:
a b c d e....iy
f g h i j....iy
所需格式:
1 2 3 4 5....259
a b c d e....iy
f g h i j....iy
我试过 writerow 函数。由于是逐行解析,得到的数据如下:
1 2 3 4 5....259
a b c d e....iy
1 2 3 4 5....259
e f g h i....iy
它在每一行之后打印标题名称。
我目前用于将数据打印到文件的代码如下:
if '[' in line:
#processdata functions(converting from hex)
line = processdata
f = open("output.csv", "a+")
f.write(line)
f.close()
如果对文件的逐行解析有任何建议,我将不胜感激。我正在寻找类似 open("file.csv", "a+", header = ['1', '2','3','n'] 的东西。谢谢。
解决方案
使用熊猫
file.to_csv("gfg2.csv", header=headerList, index=False)
# importing python package
import pandas as pd
# read contents of csv file
file = pd.read_csv("gfg.csv")
print("\nOriginal file:")
print(file)
# adding header
headerList = ['id', 'name', 'profession']
# converting data frame to csv
file.to_csv("gfg2.csv", header=headerList, index=False)
# display modified csv file
file2 = pd.read_csv("gfg2.csv")
print('\nModified file:')
print(file2)
见https://www.geeksforgeeks.org/how-to-add-a-header-to-a-csv-file-in-python/
和https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html
推荐阅读
- c++ - 如何通过派生类函数从基类更改向量
- python - 如何在 python selenium 中使用样式属性查找 webelement
- bootstrap-modal - p-日历隐藏在 Angular 7 中 bs-modal 的容器面板下
- c# - 当前不支持“Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSql”方法
- reactjs - 与使用 jest 和 materialUi 组件测试我的组件 React 测试库相关
- r - `table`未以矩阵格式显示
- python - 使用 Azure DevOps API 更新 TFS/Azure DevOps 测试用例步骤结果
- c# - 使用绘画方法在表单上创建运动 - 不起作用
- c# - VirusTotal 上传的文件为零字节
- jboss - Keycloak 不为事件发送电子邮件