代码之家  ›  专栏  ›  技术社区  ›  jucas85

循环中的csv编写器-Python

  •  1
  • jucas85  · 技术社区  · 7 年前

    我正在尝试使用Python中的csv writer将输出数据写入文件。当我只使用print命令时,数据看起来很好。但是当我使用 writerow 命令(第20行),文件中没有任何内容。

    我知道代码不是最漂亮的,也可能不是最有效的,但它(几乎)满足了我的需要。

    这是我的代码:

    import requests
    from BeautifulSoup import BeautifulSoup
    import csv
    
    symbols = {'AMZN', 'BAC', 'GOOG', 'RCL'}
    with open('symbols.csv', "w") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
    
    for s in symbols:
        try:
            url1 ='https://research.tdameritrade.com/grid/public/research/stocks/fundamentals?symbol='
            full_url = url1 + s
            response = requests.get(full_url)
            html = response.content
            soup = BeautifulSoup(html)
    
            for hist_div in soup.find("div", {"data-module-name": "HistoricGrowthAndShareDetailModule"}):
                EPS = hist_div.find('label').text
                print (s + '    ' + EPS) #this works and prints out good looking data
                #writer.writerow([s,EPS])<<this doesn't print anything to file
        except Exception as e:
            continue
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   cs95 abhishek58g    7 年前

    这就是你得到的,这是有道理的。如果你注意到的话,在你打电话的时候 writer.writerow ,您已关闭该文件。好吧,您没有明确地这样做,但是由于您使用 with 在上下文管理器中,一旦 具有 块已退出,因此任何写入操作都将在关闭的文件上进行,这是不可能的。

    如果希望这样做,则需要将循环(及其内部的所有内容)放置在 具有 块(因此,缩进更深一层)。

    with open('symbols.csv', "w") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for s in symbols:
           ...   # call writer.writerow inside the block, while the file is open
    
        2
  •  0
  •   Rahul    7 年前

    您正在尝试在关闭的csv文件上写入。试着用block做些什么。

    symbols = {'AMZN', 'BAC', 'GOOG', 'RCL'}
    with open('symbols.csv', "w") as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for s in symbols:
            ... rest of your code