Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding/appending additional information in a column for a csv file

I need to store/add/append additional information in a specific column in a csv file with out using csv.DictReader. In a function.

For example:

Sample csv file:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ cat file.csv
"A","B","C","D","E"
"a1","b1","c1","d1","e1"
"a2","b2","c2","d2","e2"

Code:

sample = ['dx;dy']
with(openfile.csv, "r") as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    headers = next(reader)
    for row in reader:
        #sample.append(to the column D)

The Output should look like this:

$ cat file.csv
    "A","B","C","D","E"
    "a1","b1","c1","d1;dx;dy","e1"
    "a2","b2","c2","d2;dx;dy","e2"

>Solution :

Since you know the header of the column you want to append to, you can find its index in the headers row, and then modify that element of each row.

append_to_column = 'D'
separator = ';'
sample = ['dx;dy']
with open('file.csv', "r") as csvfile, open("outfile.csv", "w") as outfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    headers = next(reader)
    writer = csv.writer(outfile, delimiter=',', quotechar='"')
    col_index = headers.index(append_to_column)
    for row in reader:
        value = row[col_index]
        new_value = value + separator + sample[0]
        row[col_index] = new_value
        writer.writerow(row)

Which gives:

A,B,C,D,E
a1,b1,c1,d1;dx;dy,e1
a2,b2,c2,d2;dx;dy,e2

Note that this file doesn’t have quotes because they aren’t required, since the fields don’t contain any commas. If you want to force the csv.writer to write quotes, you can add the quoting=csv.QUOTE_ALL argument to the csv.writer() call, like so: writer = csv.writer(outfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
Then, you’ll get:

"A","B","C","D","E"
"a1","b1","c1","d1;dx;dy","e1"
"a2","b2","c2","d2;dx;dy","e2"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading