-1

How to replace entire column with python.

example i have a csv file like below

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

now i need to replace all values for group column to d

1
  • 1
    come on it's not so difficult to try something with all the examples out there. Commented Aug 7, 2018 at 8:13

2 Answers 2

1

Here an answer with the python csv module. It just reads out a csv file, changes the "Group" column and writes the row to a new csv file.

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)
Sign up to request clarification or add additional context in comments.

Comments

0

Maybe you can just ignore the value in group column and adding a "d" to entry. For example:

group = 'd'
with open('file.csv') as fd:
    fd.readline() #ignore header line
    for line in fd:
        id, name, age, _ = line.split(',')
        print([id, name, age, gruop])

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.