简体   繁体   English

FileNotFoundError: [Errno 2] 文件 stock_dfs/BRK.B.csv 不存在:如果文件不存在如何调整代码:

[英]FileNotFoundError: [Errno 2] File stock_dfs/BRK.B.csv does not exist: how to adjust code if file doesn't exist:

import bs4 as bs
import datetime as dt
import os
import pandas as pd
import pandas_datareader.data as web
import pickle
import requests


def save_sp500_tickers():
resp = 
requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
soup = bs.BeautifulSoup(resp.text, 'lxml')
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
    ticker = row.findAll('td')[0].text
    tickers.append(ticker)
with open("sp500tickers.pickle", "wb") as f:
    pickle.dump(tickers, f)
return tickers


 # save_sp500_tickers()
def get_data_from_yahoo(reload_sp500=False):
if reload_sp500:
    tickers = save_sp500_tickers()
else:
    with open("sp500tickers.pickle", "rb") as f:
        tickers = pickle.load(f)
if not os.path.exists('stock_dfs'):
    os.makedirs('stock_dfs')

start = dt.datetime(2010, 1, 1)
end = dt.datetime.now()
for ticker in tickers:
    # just in case your connection breaks, we'd like to save our progress!
    if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):
        df = web.DataReader(ticker, 'yahoo', start, end)
        df.reset_index(inplace=True)
        df.set_index("Date", inplace=True)
        df = df.drop("Symbol", axis=1)
        df.to_csv('stock_dfs/{}.csv'.format(ticker))
    else:
        print('Already have {}'.format(ticker))


def compile_data():
with open("sp500tickers.pickle", "rb") as f:
    tickers = pickle.load(f)

main_df = pd.DataFrame()

for count, ticker in enumerate(tickers):
    df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))

error occurs here it states "File stock_dfs/BRK.B.csv does not exist" but it wasnt imported / stored locally in the first place so why is this an issue?这里发生错误,它指出“文件 stock_dfs/BRK.B.csv 不存在”但它不是首先在本地导入/存储的,为什么这是一个问题? full error at the bottom底部完全错误

    df.set_index('Date', inplace=True)

    df.rename(columns={'Adj Close': ticker}, inplace=True)
    df.drop(['Open', 'High', 'Low', 'Close', 'Volume'], 1, inplace=True)

    if main_df.empty:
        main_df = df
    else:
        main_df = main_df.join(df, how='outer')

    if count % 10 == 0:
        print(count)
print(main_df.head())
main_df.to_csv('sp500_joined_closes.csv')


compile_data() 

pandas_datareader\compat__init__.py:7: FutureWarning: pandas.util.testing is deprecated. pandas_datareader\compat__init__.py:7: FutureWarning: pandas.util.testing 已弃用。 Use the functions in the public API at pandas.testing instead.请改用 pandas.testing 中的公共 API 中的函数。 from pandas.util.testing import assert_frame_equal 0 10 20 30 40 50 60 Traceback (most recent call last): File "C:\Users\Desktop\Python tutorials\Python finance Examples\py3tutorialSP500manip.py", line 75, in compile_data() File "C:\Users\Desktop\Python tutorials\Python finance Examples\py3tutorialSP500manip.py", line 57, in compile_data df = pd.read_csv('stock_dfs/{}.csv'.format(ticker)) File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py", line 676, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py", line 448, in _read parser = TextFileReader(fp_or_buf, **kwds) File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py", line 880, in init self._make_engine(self.engine) File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py", line 1114, in _make_engine s from pandas.util.testing import assert_frame_equal 0 10 20 30 40 50 60 Traceback(最近一次调用最后):文件“C:\用户\桌面\Python教程\Python金融示例\py3tutorialSP500manip.py”,第75行,在compile_data( ) 文件“C:\Users\Desktop\Python 教程\Python 金融示例\py3tutorialSP500manip.py”,第 57 行,在 compile_data df = pd.read_csv('stock_dfs/{}.csv'.format(ticker)) 文件“C :\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py",第 676 行,在 parser_f 返回 _read(filepath_or_buffer, kwds) 文件“C:\Users\AppData\ Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py”,第 448 行,在 _read parser = TextFileReader(fp_or_buf, **kwds) 文件“C:\Users\AppData\Local\Programs \Python\Python38\lib\site-packages\pandas\io\parsers.py”,第 880 行,在init self._make_engine(self.engine) 文件“C:\Users\AppData\Local\Programs\Python\Python38\ lib\site-packages\pandas\io\parsers.py",第 1114 行,在 _make_engine 中elf._engine = CParserWrapper(self.f, **self.options) File "C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py", line 1891, in init self._reader = parsers.TextReader(src, **kwds) File "pandas_libs\parsers.pyx", line 374, in pandas._libs.parsers.TextReader. elf._engine = CParserWrapper(self.f, **self.options) 文件“C:\Users\AppData\Local\Programs\Python\Python38\lib\site-packages\pandas\io\parsers.py”,第 1891 行,在init self._reader = parsers.TextReader(src, **kwds) 文件“pandas_libs\parsers.pyx”,第 374 行,在 pandas._libs.parsers.TextReader 中。 cinit File "pandas_libs\parsers.pyx", line 674, in pandas._libs.parsers.TextReader._setup_parser_source FileNotFoundError: [Errno 2] File stock_dfs/BRK.B.csv does not exist: 'stock_dfs/BRK.B.csv' cinit 文件“ pandas_libs \parsers.pyx”,第 674 行,在 pandas._libs.parsers.TextReader._setup_parser_source FileNotFoundError:[Errno 2] 文件 stock_dfs/BRK.B.Z628CB5675FF524F3E719B7AA2E88FE3 不存在:

following this tutorial:按照本教程:

https://pythonprogramming.net/combining-stock-prices-into-one-dataframe-python-programming-for-finance/ https://pythonprogramming.net/combining-stock-prices-into-one-dataframe-python-programming-for-finance/

Right before the error occurs, a call is made to pd.read_csv() :在错误发生之前,调用pd.read_csv()

for count, ticker in enumerate(tickers):
    df = pd.read_csv('stock_dfs/{}.csv'.format(ticker))

The error occurs when ticker is 'BRK.B' and the program attempts to set read data from 'stocks_dfs/BRK.B.csv' .ticker'BRK.B'并且程序尝试设置从'stocks_dfs/BRK.B.csv'读取数据时,会发生错误。

The error message is saying that there is no stocks_dfs/BRK.B.csv file on your machine.错误消息是说您的机器上没有stocks_dfs/BRK.B.csv文件。 This is puzzling since this bit of code should have downloaded all the necessary files:这令人费解,因为这段代码应该已经下载了所有必要的文件:

for ticker in tickers:
    # just in case your connection breaks, we'd like to save our progress!
    if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):
        df = web.DataReader(ticker, 'yahoo', start, end)
        df.reset_index(inplace=True)
        df.set_index("Date", inplace=True)
        df = df.drop("Symbol", axis=1)
        df.to_csv('stock_dfs/{}.csv'.format(ticker))
    else:
        print('Already have {}'.format(ticker))

Make sure you ran the download code (directly above) in the same directory you are running the read code (top).确保您在运行读取代码(顶部)的同一目录中运行下载代码(正上方)。 To run a quick check, see if there exists a folder called stock_dfs/ in you working directory.要进行快速检查,请查看您的工作目录中是否存在名为stock_dfs/的文件夹。 That folder should contain files like GOOGL.csv , FB.csv , and specifically BRK.B.csv .该文件夹应包含诸如GOOGL.csvFB.csv类的文件,特别是BRK.B.csv

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Filenotfounderror文件b'.csv'不存在 - Filenotfounderror File b'.csv' does not exist Python 错误“FileNotFoundError: [Errno 2] File b Usuarios.csv' 不存在:b Usuarios.csv'” - Python error "FileNotFoundError: [Errno 2] File b Usuarios.csv' does not exist: b Usuarios.csv'" FileNotFoundError:[Errno 2] 文件 b'smallsample.csv' 不存在:b'smallsample.csv' - FileNotFoundError: [Errno 2] File b'smallsample.csv' does not exist: b'smallsample.csv' 随机得到 FileNotFoundError: [Errno 2] 文件不存在 - randomly get FileNotFoundError: [Errno 2] File does not exist Python:FileNotFoundError:文件b'fleet.csv'不存在 - Python : FileNotFoundError: File b'fleet.csv' does not exist Pandas 无法打开 csv 文件:FileNotFoundError:[Errno 2] 文件 xyz.csv 不存在: - Pandas cant open csv file :FileNotFoundError: [Errno 2] File xyz.csv does not exist: FileNotFoundError:[Errno 2] 文件媒体/StateData.csv 不存在:'media/StateData.csv' - FileNotFoundError: [Errno 2] File media/StateData.csv does not exist: 'media/StateData.csv' FileNotFoundError: [Errno 2] 文件 b"stock_df - FileNotFoundError: [Errno 2] File b"stock_df FileNotFoundError: [Errno 2] 文件 bands.csv 不存在:'bands.csv' - FileNotFoundError: [Errno 2] File bands.csv does not exist: 'bands.csv' Python:FileNotFoundError:[Errno 2] 没有这样的文件或目录:当目录确实存在时 - Python: FileNotFoundError: [Errno 2] No such file or directory: when directory does exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM