首页 > 解决方案 > 蟒蛇 | 如何在创建 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'] 的东西。谢谢。

标签: pythoncsvheaderfile-handling

解决方案


使用熊猫

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


推荐阅读