Reputation: 3538
When this writes to a CSV file, its writing each letter into its own cell. Any thoughts on how to fix this?
I'm trying to write 'name' to its own cells.
Thanks!
import json
import csv
from unidecode import unidecode
def main():
csv_writer = open_csv() #returns the functionality to write to a csv
str_data = []
with open('location') as f:
for line in f:
str_data.append(json.loads(line))
data = str_data[0]
for item in data['contacts']:
linkedin_name = unidecode(name(item))
write_to_csv(csv_writer, linkedin_name)
def name(item):
name = item['name']
return name
def open_csv():
final_csv = open('test.csv', 'wb')
csv.writer = csv.writer(final_csv)
return csv.writer
def write_to_csv(csv_writer, linkedin_name):
csv_writer.writerow(linkedin_name)
if __name__ == '__main__':
main()
Upvotes: 1
Views: 199
Reputation: 2356
The line:
csv_writer.writerow(linkedin_name)
Is expecting a list. Try changing it to:
csv_writer.writerow([linkedin_name])
Upvotes: 2
Reputation: 279195
csv_writer.writerow([linkedin_name])
You can pass any iterable to writerow
, and it will print one cell per element. A string is iterable, and the elements are individual characters, so that's why your current code doesn't work. A list is the most convenient way to write something iterable with one specified element. You could just as well pass a tuple, but the syntax for a one-element tuple is a little unpleasant: csv_writer.writerow((linkedin_name,))
Upvotes: 3