Unable to append file in pythonHow can I represent an 'Enum' in Python?How do I use raw_input in Python 3Should I put #! (shebang) in Python scripts, and what form should it take?Best way to convert string to bytes in Python 3?Way to create multiline comments in Python?What is the Python 3 equivalent of “python -m SimpleHTTPServer”Relative imports in Python 3Using Python 3 in virtualenvWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?python asyncronous images download (multiple urls)

How were the LM astronauts supported during the moon landing and ascent? What were the max G's on them during these phases?

expansion with *.txt in the shell doesn't work if no .txt file exists

Creating Darkness

Why is a dedicated QA team member necessary?

Keyboard shortcut to access contact Quick Search?

What does Kasparov mean by "I was behind in three and even in one after six games"?

Why are there not any MRI machines available in Interstellar?

Is it legal to use cash pulled from a credit card to pay the monthly payment on that credit card?

Print sums of all subsets

Why was Sauron not trying to find the Ring, and instead of preparing for war?

Replacing tongue and groove floorboards: but can't find a match

Magento2: How can I logout customer from controller?

How do I run a game when my PCs have different approaches to combat?

How can I prevent corporations from growing their own workforce?

Do Rabbis get punished in Heaven for wrong interpretations or claims?

Grid/table with lots of buttons

Can two figures have the same area, perimeter, and same number of segments have different shape?

What is the lowest speed of a bogey a jet fighter can intercept/escort?

What does "a good player" mean in the movie Training day?

Area of parallelogram = Area of square. Shear transform

Trapped in an ocean Temple in Minecraft?

How important is a good quality camera for good photography?

Send single HTML mail

Why no ";" after "do" in sh loops?



Unable to append file in python


How can I represent an 'Enum' in Python?How do I use raw_input in Python 3Should I put #! (shebang) in Python scripts, and what form should it take?Best way to convert string to bytes in Python 3?Way to create multiline comments in Python?What is the Python 3 equivalent of “python -m SimpleHTTPServer”Relative imports in Python 3Using Python 3 in virtualenvWhy is “1000000000000000 in range(1000000000000001)” so fast in Python 3?python asyncronous images download (multiple urls)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I have this script which is to pull stock prices for the last so many years from yahoo finance.



Once the code is run, i am not able to write again on the file even though it is suppose to check what exists and append.



I get the following error:
FileExistsError: [Errno 17] File exists: 'stocks_dfs'



Please advise!




'''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()


'''










share|improve this question
























  • Please post stack trace of the error, if any.

    – psinaught
    Mar 26 at 16:37











  • Try os.mkdir('stocks_dfs') instead of os.makedirs('stocks_dfs')

    – maria
    Mar 26 at 16:37












  • @psinaught File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/inderjeet/Desktop/untitled1.py", line 55, in <module> get_data_from_yahoo() File "/home/inderjeet/Desktop/untitled1.py", line 41, in get_data_from_yahoo os.makedirs('stocks_dfs') File "/usr/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode)

    – Inderjeet Singh
    Mar 26 at 20:41











  • @maria Thanks for your suggestion: os.mkdir('stocks_dfs') FileExistsError: [Errno 17] File exists: 'stocks_dfs'

    – Inderjeet Singh
    Mar 26 at 20:41


















1















I have this script which is to pull stock prices for the last so many years from yahoo finance.



Once the code is run, i am not able to write again on the file even though it is suppose to check what exists and append.



I get the following error:
FileExistsError: [Errno 17] File exists: 'stocks_dfs'



Please advise!




'''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()


'''










share|improve this question
























  • Please post stack trace of the error, if any.

    – psinaught
    Mar 26 at 16:37











  • Try os.mkdir('stocks_dfs') instead of os.makedirs('stocks_dfs')

    – maria
    Mar 26 at 16:37












  • @psinaught File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/inderjeet/Desktop/untitled1.py", line 55, in <module> get_data_from_yahoo() File "/home/inderjeet/Desktop/untitled1.py", line 41, in get_data_from_yahoo os.makedirs('stocks_dfs') File "/usr/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode)

    – Inderjeet Singh
    Mar 26 at 20:41











  • @maria Thanks for your suggestion: os.mkdir('stocks_dfs') FileExistsError: [Errno 17] File exists: 'stocks_dfs'

    – Inderjeet Singh
    Mar 26 at 20:41














1












1








1








I have this script which is to pull stock prices for the last so many years from yahoo finance.



Once the code is run, i am not able to write again on the file even though it is suppose to check what exists and append.



I get the following error:
FileExistsError: [Errno 17] File exists: 'stocks_dfs'



Please advise!




'''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()


'''










share|improve this question
















I have this script which is to pull stock prices for the last so many years from yahoo finance.



Once the code is run, i am not able to write again on the file even though it is suppose to check what exists and append.



I get the following error:
FileExistsError: [Errno 17] File exists: 'stocks_dfs'



Please advise!




'''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()


'''







python-3.x yahoo-finance






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 16:33







Inderjeet Singh

















asked Mar 26 at 11:21









Inderjeet SinghInderjeet Singh

85 bronze badges




85 bronze badges












  • Please post stack trace of the error, if any.

    – psinaught
    Mar 26 at 16:37











  • Try os.mkdir('stocks_dfs') instead of os.makedirs('stocks_dfs')

    – maria
    Mar 26 at 16:37












  • @psinaught File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/inderjeet/Desktop/untitled1.py", line 55, in <module> get_data_from_yahoo() File "/home/inderjeet/Desktop/untitled1.py", line 41, in get_data_from_yahoo os.makedirs('stocks_dfs') File "/usr/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode)

    – Inderjeet Singh
    Mar 26 at 20:41











  • @maria Thanks for your suggestion: os.mkdir('stocks_dfs') FileExistsError: [Errno 17] File exists: 'stocks_dfs'

    – Inderjeet Singh
    Mar 26 at 20:41


















  • Please post stack trace of the error, if any.

    – psinaught
    Mar 26 at 16:37











  • Try os.mkdir('stocks_dfs') instead of os.makedirs('stocks_dfs')

    – maria
    Mar 26 at 16:37












  • @psinaught File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/inderjeet/Desktop/untitled1.py", line 55, in <module> get_data_from_yahoo() File "/home/inderjeet/Desktop/untitled1.py", line 41, in get_data_from_yahoo os.makedirs('stocks_dfs') File "/usr/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode)

    – Inderjeet Singh
    Mar 26 at 20:41











  • @maria Thanks for your suggestion: os.mkdir('stocks_dfs') FileExistsError: [Errno 17] File exists: 'stocks_dfs'

    – Inderjeet Singh
    Mar 26 at 20:41

















Please post stack trace of the error, if any.

– psinaught
Mar 26 at 16:37





Please post stack trace of the error, if any.

– psinaught
Mar 26 at 16:37













Try os.mkdir('stocks_dfs') instead of os.makedirs('stocks_dfs')

– maria
Mar 26 at 16:37






Try os.mkdir('stocks_dfs') instead of os.makedirs('stocks_dfs')

– maria
Mar 26 at 16:37














@psinaught File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/inderjeet/Desktop/untitled1.py", line 55, in <module> get_data_from_yahoo() File "/home/inderjeet/Desktop/untitled1.py", line 41, in get_data_from_yahoo os.makedirs('stocks_dfs') File "/usr/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode)

– Inderjeet Singh
Mar 26 at 20:41





@psinaught File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "/usr/lib/python3/dist-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "/home/inderjeet/Desktop/untitled1.py", line 55, in <module> get_data_from_yahoo() File "/home/inderjeet/Desktop/untitled1.py", line 41, in get_data_from_yahoo os.makedirs('stocks_dfs') File "/usr/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode)

– Inderjeet Singh
Mar 26 at 20:41













@maria Thanks for your suggestion: os.mkdir('stocks_dfs') FileExistsError: [Errno 17] File exists: 'stocks_dfs'

– Inderjeet Singh
Mar 26 at 20:41






@maria Thanks for your suggestion: os.mkdir('stocks_dfs') FileExistsError: [Errno 17] File exists: 'stocks_dfs'

– Inderjeet Singh
Mar 26 at 20:41













1 Answer
1






active

oldest

votes


















0















FileExistsError: [Errno 17] File exists: 'stocks_dfs'




You are complaining that this line fails:



 os.makedirs('stocks_dfs')


To support repeated invocations, you'll want to specify the exist_ok=True flag.






share|improve this answer























  • Thank a lot for your help. It worked!!!

    – Inderjeet Singh
    Mar 26 at 20:43










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55355935%2funable-to-append-file-in-python%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0















FileExistsError: [Errno 17] File exists: 'stocks_dfs'




You are complaining that this line fails:



 os.makedirs('stocks_dfs')


To support repeated invocations, you'll want to specify the exist_ok=True flag.






share|improve this answer























  • Thank a lot for your help. It worked!!!

    – Inderjeet Singh
    Mar 26 at 20:43















0















FileExistsError: [Errno 17] File exists: 'stocks_dfs'




You are complaining that this line fails:



 os.makedirs('stocks_dfs')


To support repeated invocations, you'll want to specify the exist_ok=True flag.






share|improve this answer























  • Thank a lot for your help. It worked!!!

    – Inderjeet Singh
    Mar 26 at 20:43













0












0








0








FileExistsError: [Errno 17] File exists: 'stocks_dfs'




You are complaining that this line fails:



 os.makedirs('stocks_dfs')


To support repeated invocations, you'll want to specify the exist_ok=True flag.






share|improve this answer














FileExistsError: [Errno 17] File exists: 'stocks_dfs'




You are complaining that this line fails:



 os.makedirs('stocks_dfs')


To support repeated invocations, you'll want to specify the exist_ok=True flag.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 26 at 16:38









J_HJ_H

6,0551 gold badge9 silver badges24 bronze badges




6,0551 gold badge9 silver badges24 bronze badges












  • Thank a lot for your help. It worked!!!

    – Inderjeet Singh
    Mar 26 at 20:43

















  • Thank a lot for your help. It worked!!!

    – Inderjeet Singh
    Mar 26 at 20:43
















Thank a lot for your help. It worked!!!

– Inderjeet Singh
Mar 26 at 20:43





Thank a lot for your help. It worked!!!

– Inderjeet Singh
Mar 26 at 20:43








Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.







Got a question that you can’t ask on public Stack Overflow? Learn more about sharing private information with Stack Overflow for Teams.



















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55355935%2funable-to-append-file-in-python%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해