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.
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.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.