import csv
with open( "example.csv" , "r") as csv_file:
csv_reader = csv.reader(csv_file)
with open("edited.csv", "w", newline='') as new_file:
csv_writer = csv.writer(new_file)
for line in csv_reader:
csv_writer.writerow(line)
Here is my code. I am able to read data from a csv file on my desktop and rewrite the same data to another csv file on designated location. But my question is, while i am re-writing the data, i want to edit/change only first columns where my titles are. I want to rename the title names and add new columns(only titles)
This is my example CSV where I want to read and take all data as it is
a) I would like to keep the same data: From A to K (including K column) check the example image above
b) I want to modify only column titles on Column L and M (at first they were Person L and Person M). In my edited file i want to change them to New Title L, New Title M
c) After the M column, i want to add extra column title names till Column T (New Title N, New Title O, New Title P, New Title Q, New Title R, New Title S, New Title T)
At the end my desired file need to look like this
So i want to read, meanwhile edit my csv and store edited new file on my desktop/etc place. So far i can only copy paste same data with python and couldn't edit or add new titles. Thanks a lot. Sorry for my inconvenience, i am a newbie on programming :)
You have to change modify in this loop.
for line in csv_reader:
new_line = modify(line)
csv_writer.writerow(new_line)
This will work because here the line
is a list of strings. So if your string is in the first column then it can be accessed using line[0]
. This is for every row. To get the current row index, enumerate
can be used. Then the code becomes
for row_index, line in enumerate(csv_reader):
new_line = modify(row_index, line)
csv_writer.writerow(new_line)
Note I added a modify
function. Now If we implement the modify
function with your logic then the problem can be solved easily.
def modify(row_index, line):
title_names = ["N", "O", "P", "Q", "R", "S", "T"]
if row_index == 0:
line[11] = "New Title L"
line[12] = "New Title M"
# Also add 7 more columns
if row_index == 0:
line.extend(["New Title %s" % n for n in title_names])
else:
# Add empty columns to make sure column size is always same.
line.extend([""] * 7)
return line