【问题标题】:Python 3 CSV not writingPython 3 CSV 不写入
【发布时间】:2015-12-28 02:00:54
【问题描述】:

当我打开 csv 文件时,我什么也看不到。这是构建 csv 文件的正确方法吗?只是想学习这一切。感谢您的所有帮助。

    import csv
    from urllib.request import urlopen
    from bs4 import BeautifulSoup

    html = urlopen("http://shop.nordstrom.com/c/designer-handbags?dept=8000001&origin=topnav#category=b60133547&type=category&color=&price=&brand=&stores=&instoreavailability=false&lastfilter=&sizeFinderId=0&resultsmode=&segmentId=0&page=1&partial=1&pagesize=100&contextualsortcategoryid=0")
    nordHandbags = BeautifulSoup(html)
    bagList = nordHandbags.findAll("a", {"class":"title"})

    f = csv.writer(open("./nordstrom.csv", "w"))
    f.writerow(["Product Title"])

    for title in bagList:
        productTitles = title.contents[0]
        f.writerow([productTitles])

【问题讨论】:

  • 您需要举例说明您正在使用的html。另外,您甚至没有看到'Product Title' 标头吗?
  • 我已经添加了 HTML。我也没有看到产品标题标题号。我正在使用 Windows 和 Python 3.4.3
  • 您检查的文件是否正确?似乎除非出现错误,否则您至少应该始终获取标题。
  • 我运行脚本时正在创建文件,这可能是个问题吗?

标签: python csv python-3.x beautifulsoup


【解决方案1】:

真的很难看出你为什么不能在该文件中至少有一个 "Product Title" 标头。您是否在启动 Python 解释器后检查文件 ?这是因为在该代码中没有明确关闭文件,并且在关闭之前,其内容可能会缓存在内存中。

更多 Pythonic 并避免这个问题,是

 with open("./nordstrom.csv", "w") as csvfile:
    f = csv.writer( csvfile)
    f.writerow(["Product Title"])
    # etc.

 pass # close the with block, csvfile is now closed.

另外(抓住稻草)你是用文本编辑器打开文件来检查它,还是只使用 Windows cmd.exe 中的type 命令?因为,如果文件不包含显式 LF,C:\wherever\ >prompt 可能会在您看到之前覆盖标题。

【讨论】:

    猜你喜欢
    • 2016-06-30
    • 1970-01-01
    • 2019-02-19
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多