我正在尝试将列表写入csv文件。 下面的代码运行并返回没有错误,但它不起作用,因为它实际上不填充列表中的东西csv文件。我可能做错了,因为我不明白。
import newspaper
import os
from newspaper import article
libya_newspaperlist = []
libya_newspaper=newspaper.build('https://www.cnn.com', memoize_article=False)
for article in libya_newspaper.articles:
libya_newspaperlist.append(article.url)
import csv
os.chdir("/users/patrickharned/")
libya_newspaper.csv = "/users/patrickharned/libya_newspaper.csv"
def write_list_to_file(libya_newspaperlist):
"""Write the list to csv file."""
with open("/users/patrickharned/libya_newspaper.csv") as outfile:
outfile.write(libya_newspaperlist)
所以我把代码更改为了。 进口报纸 进口口 来自报纸进口文章 libya_newspaperlist = [] libya_newspaper = newspaper.build(' https://www.cnn.com',memoize_article = False) 对于libya_newspaper.articles中的文章: libya_newspaperlist.append(article.url) 导入csv os.chdir(" /用户/ patrickharned /&#34) libya_newspaper.csv =" /users/patrickharned/libya_newspaper.csv" 打开(" /users/patrickharned/libya_newspaper.csv"," w")作为outfile: outfile.write(STR(libya_newspaperlist))
现在它输出到csv文件,但它只输出第一个条目而不会完成剩下的工作。有什么建议吗?
答案 0 :(得分:3)
您必须以写入模式打开文件:
with open("/users/patrickharned/libya_newspaper.csv", "w") as outfile:
outfile.write(libya_newspaperlist)