[英]csv writer in a loop - Python
我正在嘗試在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
這就是您得到的意義。 如果您會注意到,在調用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塊來做這些事情。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.