MarkF6
MarkF6

Reputation: 503

Python: Write output in a csv-file

I have the following text (as string, \t = Tab): Article_1 \t Title of Article \t author of article \n Article_2 \t Title of Art 2 \t author of article 2 \n

I'd like to save this in a csv-file s.t. I can open it in Excel. In fact, it is possible to open the file I got in Excel, but the program writes everything in the first column, but I'd like to have "art_1, art_2, ..." in the first column, the titles in the second and the authors in the third column. How can I do this?

Thanks for any help! :)

Upvotes: 0

Views: 658

Answers (2)

Achint
Achint

Reputation: 817

In case you want to use the csv module

import csv

with open("csv_file.csv", "wb") as csv_file:
  csv_writer = csv.writer(csv_file, delimiter=",")
  for str in list_of_articles:
    csv_writer.writerow(str.split("\t"))

Upvotes: 0

Gillespie
Gillespie

Reputation: 6561

If you have a string, str, one easy way is just:

with open("file.csv","w") as f:
    f.write(','.join(str.split()))

If you have multiple strings, and they are stored in a list, str_list, you could do this:

with open("file.csv","w") as f:
    for line in str_list:
        f.write(','.join(line.split()))
        f.write('\n')

If the question is how to split one monolithic string into manageable sub-strings, then that's a different question. In that case you'd want to split() on the \t and then go through the list 3 at a time.

There's also a csv python package that provides a clean way of creating csv files from python data structures.

Upvotes: 1

Related Questions