'Why is are my rows not being written to the CSV file?
With the code below the CSV file aaab.csv is created but nothing is written to it. The print(row) gives me the correct information. What am I doing wrong? I have tried writer.close() but that gives me an error.
import csv
from csv import writer
from csv import reader
dict1 = {}
dict2 = {}
duplist = []
notinlist2 = []
counta = 0
countb = 0
with open('/Users/list2.csv') as file_handler:
reader = csv.reader(file_handler)
next(reader, None) # skip header
for row in reader:
key = row[1]
counta += 1
#print(key)
if key in dict1.keys():
duplist.append(key)
else:
dict1[row[1]] = counta
reader = csv.reader(open('/Users/list1.csv','r'))
writer = csv.writer(open('/Users/aaab.csv', 'w',encoding='UTF8'))
next(reader, None) # skip header
headers = ['MVA','REG','No']
writer.writerow(headers)
for row in reader:
key = row[1]
if key in dict1.keys():
a = dict1.get(row[1])
countb += 1
row.append(a)
writer.writerow(row)
print(row)
else:
notinlist2.append(key)
writer.writerow(row)
print(row)
print(len(dict1))
print(duplist)
print(notinlist2)
print(countb)
Here is a sample CSV
MVA ,REG
8144802,BK36HNGP
5296130,BN33KWGP
3254005,BT50XBGP
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
