替换csv标头,而不删除其他行 [英] Replace csv header without deleting the other rows

查看:144
本文介绍了替换csv标头,而不删除其他行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要替换cvs文件text.csv的标题行.

I want to replace the header row of a cvs file text.csv.

header_list = ['column_1', 'column_2', 'column_3']

标题看起来像这样;

column_1, column_2, column_3

这是我的代码;

import csv
with open('text.csv', 'w') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(header_list)

csv文件的标题已正确替换.但是,csv文件中的其余行已删除.如何只替换标题,而保留其他行不变?

The header of the csv file was replaced correctly. However, the rest of the rows in the csv file were deleted. How do I replace only the header leaving the other rows intact?

我正在使用python v3.6

I am using python v3.6

推荐答案

以下是使用csv模块执行此操作的正确方法.
csv.DictReader将csv文件的内容读取到字典列表中.它带有一个可选的fieldnames参数,如果设置该参数,则会应用自定义标头,并忽略原始标头,并将其视为数据行.因此,您所需要做的就是阅读您的csv csv.DictReader写入文件,并用csv.DictWriter写入数据.您必须将reader中的第一行删除,因为它包含旧的标头并写入新的标头.不过,将新数据写入单独的文件确实很有意义.

Here is a proper way to do it using csv module.
csv.DictReader reads the content of csv file into a list of dicts. It takes an optional fieldnames argument which if set applies a custom header and ignores an original header and treats it as a data row. So, all you need to do is read your csv file with csv.DictReader and write data with csv.DictWriter. You will have to drop the first row in the reader because it contains the old header and write the new header. It does make sense to write the new data to a separate file though.

import csv

header = ["column_1", "column_2", "column_3"]

with open('text.csv', 'r') as fp:
    reader = csv.DictReader(fp, fieldnames=header)

    # use newline='' to avoid adding new CR at end of line
    with open('output.csv', 'w', newline='') as fh: 
        writer = csv.DictWriter(fh, fieldnames=reader.fieldnames)
        writer.writeheader()
        header_mapping = next(reader)
        writer.writerows(reader)

这篇关于替换csv标头,而不删除其他行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆