Python 中读取和自定义 CSV 表头
Python 中读取和自定义 CSV 表头
在 Python 中,使用 csv 库可以轻松地读取和操作 CSV 文件。
读取表头
import csv
with open('data.csv', 'r') as file:
reader = csv.reader(file)
header = next(reader) # 读取表头
print(header)
上述代码示例使用 next(reader) 函数读取 CSV 文件的第一行,并将其作为表头存储在 header 变量中。
自定义表头内容
有时我们可能需要自定义 CSV 文件的表头,例如:
header = ['column1', 'column2', 'column3'] # 自定义表头
通过以上方式,我们可以根据需要自定义 CSV 文件的表头内容。
原文地址: https://www.cveoy.top/t/topic/ejzi 著作权归作者所有。请勿转载和采集!