替换csv文件python

时间:2018-08-07 08:05:15

标签: python python-3.x csv

如何用python替换整列。

示例我有如下的csv文件

ID,Name,Age,Group
001,Member1,25,a
002,Member2,30,c
003,Member3,29,b

现在我需要将组列的所有值替换为d

2 个答案:

答案 0 :(得分:1)

以下是python csv模块的答案。它只是读取一个csv文件,更改“组”列,并将该行写入新的csv文件。

import csv
with open("foo.csv") as csv_read_file:
    reader = csv.DictReader(csv_read_file)
    with open("foo_new.csv", "w") as csv_write_file:
        writer = csv.DictWriter(csv_write_file, fieldnames=["ID", "Name", "Age", "Group"])
        writer.writeheader()
        for row in reader:
            row["Group"] = "d"
            writer.writerow(row)

答案 1 :(得分:0)

也许您可以忽略组列中的值,并在条目中添加“ d”。例如:

#Pick Length
pwordLen = random.randint(8,24)
password=[pwordLen]