循环中的 csv 编写器 - Python

csv writer in a loop - Python

我正在尝试使用 Python 中的 csv 编写器将我的输出数据写入文件。当我只使用打印命令时,数据看起来不错。但是当我使用 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

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

如果你想让它工作,循环(以及其中的所有内容)将需要放在 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

您正试图在关闭的 csv 文件上写入。尝试使用 `with 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