简体   繁体   中英

Overwrite data frame to already exists excel file using python

I'm stucked in one query, please take me out from it.

Query: I have one function which runs after every 1 minutes and it outputs a data frame. I want to convert this data frame to excel .xlsx file after every minute. In other words I want to update or rewrite that excel file.

def BANK_NIFTY_LIVE_DATA():

import threading

import numpy as np
import pandas as pd
import requests
from bs4 import BeautifulSoup 

writer = pd.ExcelWriter('try_try_try.xlsx')

Base_url = "https://www.nseindia.com/live_market/dynaContent/live_watch/option_chain/optionKeys.jsp?symbolCode=-9999&symbol=BANKNIFTY&symbol=BANKNIFTY&instrument=OPTIDX&date=-&segmentLink=17&segmentLink=17"
page = requests.get(Base_url)
soup = BeautifulSoup(page.content, "lxml")
stock_table=soup.find_all('table', id = 'octable')

stock_table=stock_table[0]

list=[]
for row in stock_table.find_all('tr'):
    for cell in row.find_all('td'):
        list.append(cell.text)

final_list = [l.replace('\t','').replace('\n','').replace('\r','').replace(',','').replace(' ','') for l in list]

while("" in final_list):
    final_list.remove("")


del final_list[924:]

f_final_list=[]
for i in final_list:
    if i=='-':
        f_final_list.append(i)

    else:
        f_final_list.append(float(i))

new_list = [f_final_list[i:i+21] for i in range(0, len(f_final_list), 21)]

df=pd.DataFrame.from_dict(new_list)
colnames=['CALLS OI','CALLS CHNG IN OI','CALLS VOLUME','CALLS IV','CALLS LTP','CALLS NET CHNG','CALLS BID QTY','CALLS BID PRICE','CALLS ASK PRICE','CALLS ASK QTY','STRIKE PRICE','PUTS BID QTY','PUTS BID PRICE','PUTS ASK PRICE','PUTS ASK QTY','PUTS NET CHNG','PUTS LTP','PUTS IV','PUTS VOLUME','PUTS CHNG IN OI','PUTS OI']
df.columns=colnames

df.to_excel(writer, sheet_name="sheet1")
writer.save()
writer.close()
print("working good")


timer=threading.Timer(20.0,BANK_NIFTY_LIVE_DATA)
timer.start()

Given what you are asking is :

import pandas as pd
def output(df1):
    df1.to_excel("d:\\output.xlsx")
def fun(i):
    df1 = pd.DataFrame([[i, 'b'], [i, 'd']],index=['row 1', 'row 2'],columns=['col 1', 'col 2'])
    output(df1)
for i in range(4):
    fun(i)

Output will be:

        col 1    col 2
row 1    3        b
row 2    3        d

the file is getting overwritten.

Use .to_excel

Its a simple function to save df in excel format.

For example check:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_excel.html

Hope it helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM