Reputation: 131
Trying to write to a csv file for an hour. Output problem: Each character has a comma after it. I'm not sure why this is happening since I've done it multiple times before
id_list = []
with open(outfile1, 'r') as f:
reader = csv.reader(x.replace('\0','') for x in f)
for row in reader:
temp = row
try:
id = temp[3]
id_list.append(id)
except (IndexError, csv.Error, KeyError) as e:
pass
with open(results1, 'w') as f:
writer = csv.writer(f)
for id in id_list:
try:
prov_data = getData()
if prov_data is None:
continue
fab = prov_data['results'][0]['fab']
man = prov_data['results'][0]['man']
serv_type = prov_data['results'][0]['serv']
writer.writerows([str(id), str(fab), str(man), str(serv_type)])
except (IndexError, KeyError,csv.Error) as e:
pass
Upvotes: 2
Views: 1994
Reputation: 8547
Replace writerows
with writerow
.
The problem is that writerows
expects a list of lists, where each inward list is a row to write. Since you're giving it a list of strings, it thinks every character in the string is a column in the csv file.
Note that you're also not using id
in your second for loop, and you are opening a file named outfile1
for reading, so you may need to rethink your names here. I would guess you want to replace the 0
s in your second for loop with id
, but I'm not sure.
Upvotes: 8