Getting Read-only excel using python - python

I am trying to read an already existing excel file, and append some data in another sheet in that excel file. however, after closing the file, when i try to manually open it and do some manual calculation etc.. it's says that excel is read-only. can you please help me.
import numpy as np
import pandas as pd
import os, glob
import datetime as dt
import yfinance as yf
from openpyxl import load_workbook
ticker = "SBIN.NS"
start = dt.datetime.today() - dt.timedelta(5000)
end = dt.datetime.today()
ohlcv_data = pd.DataFrame()
temp_ticker = yf.Ticker(ticker)
ohlcv_data = temp_ticker.history(start=start,end=end,interval='1d')
writer = pd.ExcelWriter('D:/NSE/SBI.xlsx',engine='openpyxl',mode='a')
ohlcv_data.to_excel(writer, sheet_name='yahoo_data2')
writer.close()

Related

How to write a text from excel file into an image

import pandas as pd
# read by default 1st sheet of an excel file
dataframe1 = pd.read_excel(r'E:\Images\New Folder\afec9b91-5c2f-4cab-aca8-abd7bde854e0\P_SA_C0002_DcW_R1_01_FMV_000000000000.xlsx')
print(dataframe1)
Output
Sensor Longitude Sensor Latitude Survey ID
72.69362 32.090865 P_SA_C0002_DcW_R1_01
Now I want that output to written on specific image.
from PIL import Image,ImageDraw,ImageFont
import glob
import os
images=glob.glob("E:\Images/*.jpg")
for img in images:
images=Image.open(img)
draw=ImageDraw.Draw(images)
font=ImageFont.load_default()
import pandas as pd
# read by default 1st sheet of an excel file
dataframe1 = pd.read_excel(r'E:\Images\New Folder\afec9b91-5c2f-4cab-aca8-abd7bde854e0\P_SA_C0002_DcW_R1_01_FMV_000000000000.xlsx')
#print(dataframe1)
# write ="dataframe1"
text="print"
draw.text((0,240),text,(250,250,250),font=font)
images.save(img)
I am trying to write the output on image by using above code by its not working.Please help.

Python yfinance - how remove the time zone?

I wrote this small code. How can I remove the "hours" timing in the excel ? See the screenshot below.
import os
import yfinance
import pandas as pd
from openpyxl import Workbook
from openpyxl import load_workbook
a=yfinance.download('CS.PA', interval='1mo')
print(a)
save_name="C:\\Users\\Lex02\\Desktop\\Python2\\Bourse essai_3.xlsx"
a.to_excel(save_name)
a_excel=load_workbook(filename=save_name)
ws=a_excel.active
os.system('pause')
Thank you !
Format your index:
a = yfinance.download('CS.PA', interval='1mo')
a.index = a.index.strftime('%Y-%m-%d') # Enter whatever format here

How do I get my .xlsx file I created using Pandas (python) to save to a different file location?

I've just started out with Pandas and I have gotten my xls file to convert into an xlsx file using Pandas however I now want the file to save to a different loaction such as OneDrive I was wondering if you could help me out?
Here is the code I have written for it:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
#Deleting original file
path = (r"C:\Users\MQ\Downloads\Incident Report.xls")
os.remove(path)
print("Original file has been deleted :)")
#Identifying the xls file
excel_file_1 = 'Incident Report.xls'
df_first_shift = pd.read_excel(r'C:\Users\MQ\3D Objects\New Folder\Incident Report.xls')
print(df_first_shift)
#combining data
df_all = pd.concat([df_first_shift])
print(df_all)
#Creating the .xlsx file
df_all.to_excel("Incident_Report.xlsx")
Use pd.ExcelWriter by passing in your destination path!
destination_path = "path\\to\\your\\onedrive\\filename.xlsx"
writer = pd.ExcelWriter(destination_path , engine='xlsxwriter')
df.to_excel(writer, sheet_name='sheetname')
writer.save()
To write to cloud OneDrive the following code is suggested. I did not run it but offer it as a suggestion.
REFER to www.lieben.nu's example for uploading file to onedrive`
import requests
import io
import pandas as pd
def cloudOneDrive(filename, bytesIO):
'''
Reference : https://www.lieben.nu/liebensraum/2019/04/uploading-a-file-to-onedrive-for-business-with-python/
Write to cloud (bytesIO)
'''
data = {'grant_type':"client_credentials",
'resource':"https://graph.microsoft.com",
'client_id':'XXXXX',
'client_secret':'XXXXX'}
URL = "https://login.windows.net/YOURTENANTDOMAINNAME/oauth2/token?api-version=1.0"
# FIXME: put coder top open OneDrive file here as bytes stream
r = requests.put(URL+"/"+filename+":/content", data=bytesIO, headers=headers)
if r.status_code == 200 or r.status_code == 201:
print("succeeded")
return True
else:
print("Fail", r.status_code)
fn = 'junk.xlsx'
with io.BytesIO() as bio:
with pd.ExcelWriter(bio, mode='wb') as xio:
df.to_excel(bio, sheet_name='sh1')
bio.seek(0)
cloudOneDrive(fn, bio)

Loading Data Set with Breaks

I'm trying to load a dataset with breaks in it. I am trying to find an intelligent way to make this work. I got started on it with the code i included.
As you can see, the data within the file posted on the public FTP site starts at line 11, ends at line 23818, then starts at again at 23823, and ends at 45,630.
import pandas as pd
import numpy as np
from io import BytesIO
from zipfile import ZipFile
from urllib.request import urlopen
url = urlopen("http://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/10_Portfolios_Prior_12_2_Daily_CSV.zip")
#Download Zipfile and create pandas DataFrame
zipfile = ZipFile(BytesIO(url.read()))
df = pd.read_csv(zipfile.open('10_Portfolios_Prior_12_2_Daily.CSV'), header = 0,
names = ['asof_dt','1','2','3','4','5','6','7','8','9','10'], skiprows=10).dropna()
df['asof_dt'] = pd.to_datetime(df['asof_dt'], format = "%Y%m%d")
I would ideally like the first set to have a version number "1", the second to have "2", etc.
Any help would be greatly appreciated. Thank you.

xlsxwriter issues using python 3.3 using pandas

Struggling to get xlxswriter to create multiple worksheets and use the pandas df.to_excel method to place the data in there.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import xlsxwriter
import os as os
import sqlite3 as sql
import xlrd
path = (r'C:\Users\test1\Downloads\category.xlsx') #folder
data = pd.DataFrame()
data = pd.read_excel(path,sheetname='1')
print (data.shape)
data.head()
#create excel workbook using xlsxwriter
#workbook = xlsxwriter.Workbook('hyperlink.xlsx')
writer = ExcelWriter('hyperlink.xlsx')
data.to_excel(writer,'Sheet1')
workbook.close()

Categories