EDIT:
I need to store/add/append additional information in a specific column in a csv file with out using csv.DictReader
.
If I wanted to skip a row in a column and it was empty, what do I need to do for it?
For example:
Sample csv file:
$ cat file.csv
"A","B","C","D","E"
"a1","b1","c1","d1","e1"
"a2","b2","c2","d2","e2"
"a2","b2","c2",,"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"
"a2","b2","c2",,"e2"
CodePudding user response:
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"