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 st 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! :)
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.
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"))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.