【问题标题】:Why can't I create a csv file with the csv module?为什么我不能使用 csv 模块创建 csv 文件?
【发布时间】:2018-07-13 10:46:18
【问题描述】:

我正在尝试将列表写入 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("/users/patrickharned/") libya_newspaper.csv = "/users/patrickharned/libya_newspaper.csv" 使用 open("/users/patrickharned/libya_newspaper.csv", "w") 作为输出文件: outfile.write(str(libya_newspaperlist))

现在它确实输出到 csv 文件,但它只输出第一个条目而不会做其余的。有什么建议吗?

【问题讨论】:

  • 写入文件的唯一命令是在您从不调用的函数内部。
  • 也许看到这个documentation
  • 您应该从outfile.write(libya_newspaperlist) 行中得到一个明显的异常(假设您在某处调用了write_list_to_file() 函数。错误消息是什么意思?请edit 您的问题并添加它。
  • 好吧 Prune 是正确的,我没有正确调用该函数,所以我摆脱了该函数。现在我收到此错误消息。回溯(最近一次通话):文件“/Users/patrickharned/Documents/LibyaNewspaperFEB2.py”,第 12 行,在 outfile.write(libya_newspaperlist) TypeError: write() argument must be str, not list I think i知道如何解决它,我可以输入 str(libya_newsaperlist) 吗?
  • @Harned 你的问题解决了吗?

标签: python csv


【解决方案1】:

你必须以写模式打开文件:

with open("/users/patrickharned/libya_newspaper.csv", "w") as outfile:
        outfile.write(libya_newspaperlist)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多