How to update a particular column of a row in a csv using python
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??
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.
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.
精彩评论