【问题标题】:Python DictWriter /nPython 字典编写器 /n
【发布时间】:2013-10-30 04:47:27
【问题描述】:

我正在使用以下代码,它运行良好,除了我的代码从 Excel 输出到一个 CSV 文件并且它跳过每隔一行。我在stackoverflow.com 中搜索了 csv 模块文档和其他示例,发现我需要使用 DictWriter 并将 lineterminator 设置为 '\n'。我自己将其写入代码的尝试已被挫败。

所以我想知道有没有办法让我将这个(作为 lineterminator)应用到整个文件,这样我就不会跳过任何行?如果是的话怎么办?

代码如下:

import urllib2
from BeautifulSoup import BeautifulSoup
import csv

page = urllib2.urlopen('http://finance.yahoo.com/q/ks?s=F%20Key%20Statistics').read()

f = csv.writer(open("pe_ratio.csv","w"))
f.writerow(["Name","PE"])

soup = BeautifulSoup(page)
all_data = soup.findAll('td', "yfnc_tabledata1")
f.writerow([all_data[2].getText()])

提前感谢您的帮助。

【问题讨论】:

  • “隔行跳过”是什么意思?你能给出一个示例输入、你得到的输出和想要的输出吗?

标签: python csv


【解决方案1】:

您需要使用正确的选项打开文件,csv.writer 类才能正常工作。该模块内部具有通用换行支持,因此您需要在文件级别关闭 Python 的通用换行支持。

对于 Python 2,the docs say:

如果csvfile 是一个文件对象,则必须在不同的平台上使用'b' 标志打开它。

对于 Python 3,they say

如果csvfile是一个文件对象,它应该用newline=''打开。

此外,您可能应该使用with 语句来处理打开和关闭文件,如下所示:

with open("pe_ratio.csv","wb") as f: # or open("pe_ratio.csv", "w", newline="") in Py3
    writer = csv.writer(f)

    # do other stuff here, staying indented until you're done writing to the file

【讨论】:

    【解决方案2】:

    首先,既然 Yahoo 提供了一个返回 CSV 文件的 API,也许您可​​以通过这种方式解决您的问题?例如,this URL 返回一个 CSV 文件,其中包含该行业所有股票的价格、市值、市盈率和其他指标。有一些more information in this Google Code project

    您的代码仅生成两行 CSV,因为只有两次调用 f.writerow()。如果您想要从该页面获得的唯一数据是市盈率,这几乎肯定不是最好的方法,但您应该将包含每列值的元组传递给f.writerow()。为了与您的标题行保持一致,这将类似于:

    f.writerow( ('Ford', all_data[2].getText()) )
    

    当然,这是假设市盈率总是排在第二位的。相反,如果您想要该页面上提供的所有统计信息,您可以尝试:

    # scrape the html for the name and value of each metric
    metrics = soup.findAll('td', 'yfnc_tablehead1')
    values = soup.findAll('td', 'yfnc_tabledata1')
    
    # create a list of tuples for the writerows method
    def stripTag(tag): return tag.text
    data = zip(map(stripTag, metrics), map(stripTag, values))
    
    # write to csv file
    f.writerows(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 2016-10-23
      • 2018-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多