-1

I wish to write the list files into a csv file:

a = ['0.18 man::-1_-1king|new\n', '0.19 gif::-2manchester\n', '0.177 united\n']

How can I do it?

Here are my codes :

import csv

a = ['0.18 king\n', '0.19 manchester\n', '0.177 united\n']

with open("output.csv",'wb') as resultFile: 
    wr = csv.writer(resultFile)
    wr.writerows(a)

I wanted my results to be something like this:

Column 1    Column 2
0.18            man::-1_-1king|new
0.19            gif::-2manchester
0.177           united
JJson
  • 233
  • 1
  • 4
  • 18

1 Answers1

-1

If its a simple list as shown in the example, you don't need to import csv, just try this

a = ['0.18 king\n', '0.19 manchester\n', '0.177 united\n']

with open("output.csv",'wb') as fin: 
    for row in a:
        word1, word2 = row.split()
        fin.write('%s,%s\n'%(word1,word2))

a = ['0.18 man::-1king\n', '0.19 gif::-2manchester\n', '0.177 united\n']

with open("output.tsv",'wb') as fin: 
    for row in a:
        word1, word2 = row.split()
        fin.write('%s\t%s\n'%(word1,word2))
Perseus14
  • 467
  • 1
  • 6
  • 19
  • What if one of those words contains a comma? Use the csv module to write csv files, damnit. – Aran-Fey Aug 10 '18 at 07:47
  • Yea, I have commas so somehow everything printed in according to the columns but when I have commas then it became weird. Any other alternative and thank you – JJson Aug 10 '18 at 07:48
  • I edited and include another new example when something like comma included. – JJson Aug 10 '18 at 07:53
  • Well then you probably have to use csv module unless you are ok with a tsv file (tab separated file), in which case only a small modification is necessary – Perseus14 Aug 10 '18 at 07:57
  • is it possible to make it in csv file? I would like to learn as well to understand how it works – JJson Aug 10 '18 at 07:59
  • Thank you and the previous one works but however, I tried another new problem. What about if my list contains "_"? I edited again and could you please take a look? – JJson Aug 10 '18 at 08:02
  • @JJson I don't see how an underscore could cause any problems. If you want to be tricky, add some commas and/or quotes in your data. – Aran-Fey Aug 10 '18 at 08:04
  • I tried to save it in csv file but when it happens to have the underscore. Somehow words after underscore being inserted into next column instead of the same column – JJson Aug 10 '18 at 08:08
  • @JJson Then there's something wrong with the program you're using to read the csv file. Maybe it thinks that the underscore is the separator. – Aran-Fey Aug 10 '18 at 08:12
  • But I am using normal program like microsoft to open it in excel – JJson Aug 10 '18 at 08:18
  • @JJson [There's nothing wrong with the csv.](https://repl.it/repls/UselessBisquePyramid) – Aran-Fey Aug 10 '18 at 08:24