Reputation: 899
I am trying to write into a csv file 3 things :
Restaurant,Name and Review
.
Review
is a paragraph and contains commas
in itself. When i write the file, I am getting the wrong output as the final csv file is splitting into columns based on the commas in the review column.
For example, if review was "food here is great, do try!" , this string value should come in one cell in the csv file.
However, csv file separates it into 2 cells, one before the comma and one after.
To counter this, I am trying to make my file pipe
delimited.
However, I am unable to get the output. Below is my code. Please help!
names : list containing names of those who wrote a review
restaurant : restaurant name
review : list containing reviews
Output_File = open(restaurant+'.csv', 'w')
Output_File.write("Restaurant | Name | Review | \n")
for i in range(0, final):
Output_File.write(restaurant + '|' + names[i] + '|' + review[i] + '\n')
Output_File.close()
Upvotes: 4
Views: 7552
Reputation: 18743
csv will automatically split any string on a ,
into multiple fields. In order to avoid this, you need to enclose your string containing a ,
within quotes,
Output_File.write('"{}","{}","{}"'.format(restaurant, names[i], review[i]))
This way you can still make it ,
delimited.
You can also replace ,
with any other character as a delimiter.
Upvotes: 5