循环中的csv编写器-Python

循环中的csv编写器-Python,python,csv,writer,Python,Csv,Writer,我正在尝试使用Python中的csv writer将输出数据写入文件。当我只使用print命令时,数据看起来不错。但是当我使用writerow命令(第20行)时,文件中没有任何内容 我知道代码不是最漂亮的,也可能不是最有效的,但它(几乎)满足了我的需要 这是我的密码: import requests from BeautifulSoup import BeautifulSoup import csv symbols = {'AMZN', 'BAC', 'GOOG', 'RCL'} with o

我正在尝试使用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
导入请求
从BeautifulSoup导入BeautifulSoup
导入csv
符号={'AMZN','BAC','GOOG','RCL'}
打开('symbols.csv',“w”)作为csv\u文件:
writer=csv.writer(csv_文件,分隔符=',')
对于符号中的符号:
尝试:
url1=https://research.tdameritrade.com/grid/public/research/stocks/fundamentals?symbol='
完整url=url1+s
response=requests.get(完整url)
html=response.content
soup=BeautifulSoup(html)
对于soup.find中的hist_div(“div”,{“数据模块名称”:“historicgrowthandsharedtailmodule”}):
EPS=历史分区查找('label')。文本
打印(s+“”+EPS)#此功能可以打印出好看的数据

#writer.writerow([s,EPS])这就是你得到的。如果您注意到,在调用
writer.writerow
时,您已经关闭了该文件。当然,您没有明确地执行此操作,但是由于您正在将
上下文管理器一起使用,因此一旦退出
块,文件将自动关闭,因此任何写入操作都将在关闭的文件上进行,这是不可能的

如果您希望这样做,则需要将循环(以及其中的所有内容)放置在带有
块的
中(因此,缩进更深一级)


您正在尝试在关闭的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

通过捕获异常并继续,您隐藏了问题。用一个漂亮的
ValueError:I/O操作关闭文件,从那里取出try/except,看看错误在哪里。
。然后,缩进for循环,使其位于
with
语句中。
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