📜  如何在Python中向 CSV 文件添加标题?

📅  最后修改于: 2022-05-13 01:54:33.553000             🧑  作者: Mango

如何在Python中向 CSV 文件添加标题?

CSV 文件包含表格形式的数据,其中每行包含逗号分隔值。列可能包含属于不同数据结构的值。 Python提供了广泛的方法和模块来执行 CSV 文件与Pandas数据帧的相互转换,反之亦然。 CSV 文件的标题是分配给每一列的值数组。它充当数据的行标题。最初,CSV 文件被转换为数据框,然后将标题添加到数据框。数据框的内容再次存储回 CSV 文件。

在本文中,我们将在Python中向 CSV 文件添加标题。

方法 #1:to_csv()方法中使用header参数。

首先,以列表的形式创建一个标题,然后使用to_csv()方法将该标题添加到 CSV 文件中。

以下 CSV 文件gfg.csv用于操作:

Python3
# 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)


Python3
# import required modules
import pandas as pd
import csv
  
# assign header columns
headerList = ['col1', 'col2', 'col3', 'col4']
  
# open CSV file and assign header
with open("gfg3.csv", 'w') as file:
    dw = csv.DictWriter(file, delimiter=',', 
                        fieldnames=headerList)
    dw.writeheader()
  
# display csv file
fileContent = pd.read_csv("gfg3.csv")
fileContent


输出:

创建了 CSV 文件gfg2.csv

方法#2:使用 DictWriter()方法

另一种使用DictWriter()的方法可用于将标题附加到 CSV 文件的内容。 fieldnames属性可用于指定 CSV 文件的标题,并且 delimiter 参数通过csv模块中给出的分隔符分隔值,以执行标题的添加。然后在csvwriter对象上调用writeheader()方法,而不传递任何参数。

蟒蛇3

# import required modules
import pandas as pd
import csv
  
# assign header columns
headerList = ['col1', 'col2', 'col3', 'col4']
  
# open CSV file and assign header
with open("gfg3.csv", 'w') as file:
    dw = csv.DictWriter(file, delimiter=',', 
                        fieldnames=headerList)
    dw.writeheader()
  
# display csv file
fileContent = pd.read_csv("gfg3.csv")
fileContent

输出:

创建的新 CSV 文件gfg3.csv是:

注意:此方法仅适用于空的 CSV 文件。