How to properly load an .XLS file in script - python

I have a python script that opens an .xls file to read its lines and store them in a list and then it does a bunch of other things. When I try to call it from Excel like so:
Sub SampleCall()
RunPython ("import sov_reformat;sov_reformat.sov_convert()")
End Sub
Here's the first few lines of my script:
# In[1]:
import xlwings as xw
import pandas as pd
import numpy as np
import csv
# In[2]:
def sov_convert():
wb = xw.Book.caller()
df2 = pd.read_excel("Full SOV.XLS")
temp_df = df2
I get an error:
Error
Traceback (most recent call last):
File "", line 1, in
File "...\sov_reformat.py", line 70, in
sov_convert()
File "...\sov_reformat.py", line 14, in sov_convert
df2 = pd.read_excel("Full SOV.XLS")
File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 170, in read_excel
io = ExcelFile(io, engine=engine)
File "C:\Python27\lib\site-packages\pandas\io\excel.py", line 227, in init
self.book = xlrd.open_workbook(io)
File "C:\Python27\lib\site-packages\xlrd__init__.py", line 395, in open_workbook
with open(filename, "rb") as f:
IOError: [Errno 2] No such file or directory: 'Full SOV.XLS'
I think the line that's causing this error is the following:
with open('rates.csv', 'rb') as f:
reader = csv.reader(f)
rate_combinations = list(reader)
But I don't understand why. When I run the script it does exactly what I want so I know everything else is working.

Related

Invalid argument error when using f string in path of DataFrame.to_csv()

I want to write pandas dataframe to a csv file every 10 secs. The csv file name includes the current timestamp. Here is part of the code:
import pandas as pd
import time
while True:
df = pd.read_sql_query('select * from dbo.tbl_tag_values', cnxn)
t = time.localtime()
current_time = time.strftime('%Y-%m-%dT%H:%M:%S',t)
csv_path =f'C:/Users/00_Projects/App/data-{current_time}.csv'
df.to_csv(csv_path)
time.sleep(10)
Without using f-string and a static file name, the script works fine but with the f-string I get the error:
Traceback (most recent call last):
File "c:\Users\00_Projects\App\script.py", line 24, in <module>
df.to_csv(csv_path)
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 3466, in to_csv
return DataFrameRenderer(formatter).to_csv(
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\format.py", line 1105, in to_csv
csv_formatter.save()
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\formats\csvs.py", line 237, in save
with get_handle(
File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\common.py", line 702, in get_handle
handle = open(
OSError: [Errno 22] Invalid argument: 'C:/Users/00_Projects/App/data-2023-01-02T15:33:19.csv'
I read this post How to use f string in a path location and tried Path from pathlib but got the same error.
My OS is windows.
Thanks for any help!

How to open and close an excel workbook in a python for loop using xlwings

I need to open and close the same workbook in a python for loop without necessarily saving the workbook. I tried the following in xlwings:
import xlwings as xw
for i in range(5):
print(i)
book = xw.Book()
book.app.quit()
However this will only run for the first iteration. At the second iteration I get an error:
Traceback (most recent call last):
File "D:/TEMP/SE/python/ref.py", line 5, in <module>
book = xw.Book('tree_template.xlsx')
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\main.py", line 533, in __init__
for wb in app.books:
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\main.py", line 374, in books
return Books(impl=self.impl.books)
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\_xlwindows.py", line 397, in books
return Books(xl=self.xl.Workbooks)
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\_xlwindows.py", line 313, in xl
self._xl = get_xl_app_from_hwnd(self._hwnd)
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\_xlwindows.py", line 222, in get_xl_app_from_hwnd
ptr = accessible_object_from_window(child_hwnd)
File "C:\Users\aboufira\AppData\Local\Continuum\miniconda3\envs\SE\lib\site-packages\xlwings\_xlwindows.py", line 190, in accessible_object_from_window
res = oledll.oleacc.AccessibleObjectFromWindow(
File "_ctypes/callproc.c", line 948, in GetResult
OSError: [WinError -2147467259] Unspecified error
Why does this occur? How can I get xlwings to exit out of the application without causing any problems?
Your code was almost correct, use:
import xlwings as xw
for i in range(5):
print(i)
app = xw.App(visible=True)
book = xw.Book()
app.quit()
You can also use app = xw.App(visible=False) if you want to open a workbook without showing it.
Use this to suffice the pop-ups
app.display_alerts=False

Open .h5 file in Python

I am trying to read a h5 file in Python.
The file can be found in this link and it is called 'vstoxx_data_31032014.h5'. The code I am trying to run is from the book Python for Finance, by Yves Hilpisch and goes like this:
import pandas as pd
h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r')
futures_data = h5['futures_data'] # VSTOXX futures data
options_data = h5['options_data'] # VSTOXX call option data
h5.close()
I am getting the following error:
h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r')
Traceback (most recent call last):
File "<ipython-input-692-dc4e79ec8f8b>", line 1, in <module>
h5 = pd.HDFStore('path.../vstoxx_data_31032014.h5', 'r')
File "C:\Users\Laura\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 466, in __init__
self.open(mode=mode, **kwargs)
File "C:\Users\Laura\Anaconda3\lib\site-packages\pandas\io\pytables.py", line 637, in open
raise IOError(str(e))
OSError: HDF5 error back trace
File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5F.c", line 604, in H5Fopen
unable to open file
File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5Fint.c", line 1085, in H5F_open
unable to read superblock
File "C:\aroot\work\hdf5-1.8.15-patch1\src\H5Fsuper.c", line 277, in H5F_super_read
file signature not found
End of HDF5 error back trace
Unable to open/create file 'path.../vstoxx_data_31032014.h5'
where I have substituted my working directory for 'path.../' for the purpose of this question.
Does anyone know where this error might be coming from?
In order to open a HDF5 file with the h5py module you can use h5py.File(filename). The documentation can be found here.
import h5py
filename = "vstoxx_data_31032014.h5"
h5 = h5py.File(filename,'r')
futures_data = h5['futures_data'] # VSTOXX futures data
options_data = h5['options_data'] # VSTOXX call option data
h5.close()
import os
wd=os.chdir('pah of your working directory') #change the file path to your working directory
wd=os.getcwd() #request what is the current working directory
print(wd)
if __name__ == '__main__':
# import required libraries
import h5py as h5
import numpy as np
import matplotlib.pyplot as plt
f = h5.File("hdf5 file with its path", "r")
datasetNames = [n for n in f.keys()]
for n in datasetNames:
print(n)

Unable to open xlsx file with xlrd

I am getting an error file is not support in xlrd-0.7.1.
The file is saved in xlsx format
Traceback (most recent call last):
File "C:\Users\jawed\workspace\test\Excelproject.py", line 8, in <module>
workbook=xlrd.open_workbook(file_location)
File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 425, in open_workbook
on_demand=on_demand,
File "C:\Python27\lib\site-packages\xlrd\__init__.py", line 878, in biff2_8_load
f = open(filename, open_mode)
IOError: [Errno 2] No such file or directory: 'C:\\Users\\jawed\\workspace\\IAMarks.xls'
The file doesn't exist.
Check the location of the file before calling the function:
import os
if os.path.isfile(file_location):
workbook = xlrd.open_workbook(file_location)
else:
# tell the user they've done something wrong
A possibly more Pythonic way to do it (see EAFP) is in a try/except block:
try:
workbook = xlrd.open_workbook(file_location)
except IOError as error:
print(error)
# tell the user they've done something wrong

write to an open exceldocument

I'm working on a project which I am going to write values to a exceldocument. I can write values to excel but I want to write the values to excel with the document open. If i have the doc open when trying to write to it i get an error message.
Here is my code I'm currently using.
#Write to excel
from openpyxl import Workbook
import datetime
wb = Workbook()
ws = wb.active
ws['C3'] = 1337
ws['A1'] = datetime.datetime.now()
ws['B5'] = CIRCLES
ws['B4'] = "Red puck"
wb.save("sample.xlsx")
And the error message when i have the doc. opened when trying to write to it.
Traceback (most recent call last):
File "C:\Users\RU21\Desktop\Röda puckar\Förbindelse med RR.py", line 302, in <module>
wb.save("sample.xlsx")
File "C:\Python27\lib\site-packages\openpyxl\workbook\workbook.py", line 280, in save
save_workbook(self, filename)
File "C:\Python27\lib\site-packages\openpyxl\writer\excel.py", line 211, in save_workbook
writer.save(filename)
File "C:\Python27\lib\site-packages\openpyxl\writer\excel.py", line 193, in save
archive = ZipFile(filename, 'w', ZIP_DEFLATED)
File "C:\Python27\lib\zipfile.py", line 756, in __init__
self.fp = open(file, modeDict[mode])
IOError: [Errno 13] Permission denied: 'sample.xlsx'

Categories

Resources