【问题标题】:Unable to append file in python无法在python中附加文件
【发布时间】:2019-03-26 11:21:57
【问题描述】:

我有这个脚本,用于从雅虎财经提取过去这么多年的股价。

代码运行后,我无法在文件上再次写入,即使假设检查存在并附加。

我收到以下错误: FileExistsError:[Errno 17] 文件存在:'stocks_dfs'

请指教!

'''python import bs4 as bs import pickle import requests import datetime as dt import pandas as pd import os import pandas_datareader.data as web from time import sleep

def save_sp500_tickers():
    resp = requests.get('https://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')[1].text
        tickers.append(ticker)

    with open("sp500ticker.pickle", "wb") as f:
        pickle.dump(tickers,f)

    print (tickers)

    return tickers
#save_sp500_tickers()

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

    start = dt.datetime(2016,1,1)
    end = dt.datetime.now()

    for ticker in tickers:
        print(ticker)

        if not os.path.exists('stocks_dfs/{}.csv'.format(ticker)):
            df = web.DataReader(ticker,'yahoo', start, end)
            df.to_csv('stocks_dfs/{}.csv'.format(ticker))
        else:
            print('Already have {}'.format(ticker))

get_data_from_yahoo()

'''

【问题讨论】:

  • 请发布错误的堆栈跟踪,如果有的话。
  • 试试 os.mkdir('stocks_dfs') 而不是 os.makedirs('stocks_dfs')
  • @psinaught File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py",第 705 行,在运行文件 execfile(filename, namespace) File "/usr/ lib/python3/dist-packages/spyder/utils/site/sitecustomize.py”,第 102 行,在 execfile exec(compile(f.read(), filename, 'exec'), namespace) 文件“/home/inderjeet/ Desktop/untitled1.py”,第 55 行,在 get_data_from_yahoo() 文件中“/home/inderjeet/Desktop/untitled1.py”,第 41 行,在 get_data_from_yahoo os.makedirs('stocks_dfs') 文件中“/usr/lib /python3.6/os.py",第 220 行,在 makedirs mkdir(name, mode)
  • @maria 感谢您的建议:os.mkdir('stocks_dfs') FileExistsError: [Errno 17] File exists: 'stocks_dfs'

标签: python-3.x yahoo-finance


【解决方案1】:

FileExistsError: [Errno 17] 文件存在:'stocks_dfs'

你抱怨这条线失败了:

    os.makedirs('stocks_dfs')

为了支持重复调用,您需要指定 exist_ok=True 标志。

【讨论】:

    猜你喜欢
    • 2013-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-25
    • 1970-01-01
    • 2018-09-10
    相关资源
    最近更新 更多