Python 3.x Python:写入文件失败,没有错误-获取空文件

Python 3.x Python:写入文件失败,没有错误-获取空文件,python-3.x,Python 3.x,这段代码似乎工作得很好,控制台完全满足了我的需要,没有任何错误。然而,当我试图用excel打开它时,它会给我一个空文件 import csv import urllib.request from bs4 import BeautifulSoup f = open('aapl_analyst_estimates', 'w', newline= '') writer = csv.writer(f) soup = BeautifulSoup(urllib.request.urlopen('https

这段代码似乎工作得很好,控制台完全满足了我的需要,没有任何错误。然而,当我试图用excel打开它时,它会给我一个空文件

import csv
import urllib.request
from bs4 import BeautifulSoup
f = open('aapl_analyst_estimates', 'w', newline= '')
writer = csv.writer(f)

soup = BeautifulSoup(urllib.request.urlopen('https://www.marketwatch.com/investing/stock/aapl/analystestimates').read(), 'lxml')

tbody = soup('table', {'class':'snapshot'})[0].find_all('tr')

for row in tbody:
    cols = row.findChildren(recursive=False)
    cols = [ele.text.strip() for ele in cols]
    writer.writerow(cols)
    print(cols)

f.close()

这对我来说很好。我得到以下输出:

['Number of Ratings:', '41', 'Current Quarters Estimate:', '4.17']
['FY Report Date:', '9 / 2019', "Current Year's Estimate:", '11.99']
["Last Quarter's Earnings:", '2.91', 'Median PE on CY Estimate:', '12.88']
['Year Ago Earnings:', '11.75', 'Next Fiscal Year Estimate:', '13.34']
['', '', 'Median PE on Next FY Estimate:', '11.37']

对不起,我没有更彻底地回答我的问题。输出很好,但是当我用Excel打开它时,它会给我一个空文件。它在Linux中用LibreOffice打开很好。这可能是Windows上Excel的扩展问题。尝试将该文件重命名为aapl_analyst_estimates.csv。就这么简单!非常感谢你!