0

I am having a csv file with the following contents

1,2,3,4
a,b,c,d
w,x,y,z

And i want to update this csv file contents to

1,2,3,4
a,b,c,d,k
w,x,y,z

Can someone please share Python code for this update process??

2 Answers 2

1

Using the csv library, we read in the data, convert it to a list of lists, append the k to the relevant list, then write it out again.

import csv

data = csv.reader(open("input.csv"))

l = list(data)    
l[1].append("k")

our_writer = csv.writer(open("output.csv", "wb"))

our_writer.writerows(l)

While the csv library isn't completely necessary for your toy case, it's often good to use the approach that scales well.

Sign up to request clarification or add additional context in comments.

1 Comment

For generality you might find with statement helpful to close the files properly. To update the file inplace you could write to a temporary file and rename it on success. You should use 'wb' mode for the output file. If you load all rows in memory then writer.writerows() allows you to write all the rows at once.
1

You don't need csv for such a simple case:

# sed '2s/$/,k/'
import fileinput
for lineno, line in enumerate(fileinput.input(inplace=True), start=1):
    if lineno == 2:
       line = line.rstrip('\n') + ",k\n"
    print line,

Example:

$ python update_2nd_line.py data_to_update.csv

It updates data_to_update.csv file inplace.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.