[英]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 我有以下文本(作为字符串,\\ t =制表符):Article_1 \\ t文章标题\\ t文章作者\\ n Article_2 \\ t艺术标题2 \\ t第二条作者\\ n
I'd like to save this in a csv-file st I can open it in Excel. 我想将其保存在一个csv文件中,因为我可以在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. 实际上,可以打开我在Excel中获得的文件,但是该程序将所有内容写在第一列中,但是我想在第一列中包含“ art_1,art_2,...”,标题位于第二和第三列中的作者。 How can I do this? 我怎样才能做到这一点?
Thanks for any help! 谢谢你的帮助! :) :)
If you have a string, str
, one easy way is just: 如果您有字符串str
,那么一种简单的方法就是:
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: 如果您有多个字符串,并且它们存储在str_list
列表中, str_list
可以执行以下操作:
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. 在这种情况下,您希望在\\t
上split()
,然后一次浏览列表3。
There's also a csv python package that provides a clean way of creating csv files from python data structures. 还有一个csv python软件包,提供了一种从python数据结构创建csv文件的干净方法。
In case you want to use the csv module 如果您想使用csv模块
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"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.