In excel or libreoffice cal, a cell can have multiple line entries.
Row Fruit Like/Dislike
--- ---------- ------------
1 apple Like
orange
2 pineapple Dislike
3 kiwi Like
banana
4 starfruit Dislike
I had first saved the spreadsheet as a "test.csv" file.
Next, I used Python3's csv module to read in the file. Assuming I had changed pineapple preference to "Like". Thereafter, I want to write out the amended data to a new csv file.
How do I write data to the new csv without the following issue?
Row Fruit Like/Dislike
--- ---------- ------------
1 apple Like
2 orange
3 pineapple Like
4 kiwi Like
5 banana
6 starfruit Dislike
Desired outcome:
Row Fruit Like/Dislike
--- ---------- ------------
1 apple Like
orange
2 pineapple Like
3 kiwi Like
banana
4 starfruit Dislike
The command that I had used are:
with open("out.csv", "w", newline='\n', encoding='utf_8' ) as out:
for v in data.values():
out.write( f'{v.number},{v.results["Fruit"]},{v.results["Choice"]}\n' )
What is the correct command to use?
As mentioned by @Danny_ds, I needed to use python3's csv writer. Also, I needed to set the writer's keyword dialect='excel'
. That solved my issued. So my command finally looked like this:
with open( "out.csv", 'w', newline='', encoding='utf-8' ) as csvfile:
csvwriter = csv.writer( csvfile, dialect='excel' ) #Use csv writer with excel dialect.
for v in data.values():
csvwriter.write( [v.number,v.results["Fruit"],v.results["Choice"]] )