Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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! :)

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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.

share|improve this answer

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"))
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.