I am opening a csv called Remarks_Drug.csv
which contains product names and mapped
filenames in consecutive columns. I am doing some operations on the product column
to remove all string content after +
character. After stripping the string from +
characters, I am storing the result in a variable called product_patterns
.
Now I am opening a new csv
and I want to write the output from the for loop into
two columns, the first one containing the product_patterns
and the second one containing
the corresponding filenames
.
What I am getting as output now is only the last row of the output csv
that I am looking for.
I think I am not looping properly so that each row of product_patterns
and filename gets
appended in the output csv
file.
Can someone please help me with this.
Attaching code below:
import csv
with open('Remarks_Drug.csv', newline='', encoding ='utf-8') as myFile:
reader = csv.reader(myFile)
for row in reader:
product = row[0].lower()
#print('K---'+ product)
filename = row[1]
product_patterns = ', '.join([i.split("+")[0].strip() for i in product.split(",")])
#print(product_patterns, filename)
with open ('drug_output100.csv', 'a') as csvfile:
fieldnames = ['product_patterns', 'filename']
print(fieldnames)
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
print(writer)
#writer.writeheader()
writer.writerow({'product_patterns':product_patterns, 'filename':filename})
Sample input:
Film-coated tablet + TERIFLUNOMIDE, 2011-07-18 - Received approval letter_EN.txt
Film-coated tablet + VANDETANIB, 2013-12-14 RECD Eudralink_Caprelsa II-28 - RSI - 14.12.2017.txt
Solution for injection + MenQuadTT, 395_EU001930-PIP01-16_2016-02-22.txt
Solution for injection + INSULIN GLARGINE, 2017-11-4 Updated PR.txt
Solution for injection + INSULIN GLARGINE + LIXISENATIDE, 2017 12 12 Email Approval Texts - SA1006-.txt
csv.DictWriter
uses a dictionary for each row (with keys being the field names and values being the value for the corresponding cell), and you've only written one row. – Coparcenary