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'
Related
I have a couple of excel files I want to merge into one.
I need the second column on all the files to be copied into separate columns in a new Microsoft Excel file.
For this, I am using the openpyxl library in a python script.
This is my code:
import os
from openpyxl import load_workbook
def mergeDataFiles():
path = "C:\\Users\\ethan\\Desktop\\Benzoyl Chloride\\Benzoyl Chloride"
# source excel files
origin_files = list()
for path, subdirs, files in os.walk(path):
for file_index in range(len(files)):
origin_files.append(files[file_index])
# destination excel file
destination_file = path + ".xlsx"
destination_workbook = load_workbook(destination_file)
destination_sheet = destination_workbook["Sheet1"]
# copy data from source files to destination file
for origin_file_index in range(1, len(origin_files)):
origin_workbook = load_workbook(path + "\\" + origin_files[origin_file_index - 1])
origin_sheet = origin_workbook['Data']
destination_sheet.cell(row=1, column=origin_file_index).value = origin_files[origin_file_index - 1]
for i in range(1, 500):
# read cell value from source excel file
data = origin_sheet.cell(row=i, column=2)
# write the value to destination excel file
destination_sheet.cell(row=i + 1, column=origin_file_index).value = data.value
# saving the destination excel file
destination_workbook.save(destination_file)
if __name__ == "__main__":
mergeDataFiles()
When I run the code, I get an error on the last line in the function: OSError: [Errno 9] Bad file descriptor.
Full traceback:
C:\Users\ethan\.venv\Scripts\python.exe "C:/Users/ethan/Coding/Python/Copy Excel Data/main.py"
Traceback (most recent call last):
File "C:\Users\ethan\Coding\Python\Copy Excel Data\main.py", line 32, in <module>
mergeDataFiles()
File "C:\Users\ethan\Coding\Python\Copy Excel Data\main.py", line 28, in mergeDataFiles
destination_workbook.save(destination_file)
File "C:\Users\ethan\.venv\Lib\site-packages\openpyxl\workbook\workbook.py", line 407, in save
save_workbook(self, filename)
File "C:\Users\ethan\.venv\Lib\site-packages\openpyxl\writer\excel.py", line 293, in save_workbook
writer.save()
File "C:\Users\ethan\.venv\Lib\site-packages\openpyxl\writer\excel.py", line 275, in save
self.write_data()
File "C:\Users\ethan\.venv\Lib\site-packages\openpyxl\writer\excel.py", line 67, in write_data
archive.writestr(ARC_APP, tostring(props.to_tree()))
File "C:\Program Files\Python311\Lib\zipfile.py", line 1830, in writestr
with self.open(zinfo, mode='w') as dest:
File "C:\Program Files\Python311\Lib\zipfile.py", line 1204, in close
self._fileobj.seek(self._zinfo.header_offset)
OSError: [Errno 9] Bad file descriptor
Exception ignored in: <function ZipFile.__del__ at 0x000001D101443D80>
Traceback (most recent call last):
File "C:\Program Files\Python311\Lib\zipfile.py", line 1870, in __del__
self.close()
File "C:\Program Files\Python311\Lib\zipfile.py", line 1892, in close
self._fpclose(fp)
File "C:\Program Files\Python311\Lib\zipfile.py", line 1992, in _fpclose
fp.close()
OSError: [Errno 9] Bad file descriptor
Process finished with exit code 1
I have tried changing the file names and locations, having the destination file open and closed, scouring the internet for solutions and at this point I'm not sure what else I can try.
I am running the code on Windows 10 22H2, with an intel i5 cpu.
Please assist me with this issue, if you know how to solve it.
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
I have this problem, I'm trying to run the script to download Springers free books [https://towardsdatascience.com/springer-has-released-65-machine-learning-and-data-books-for-free-961f8181f189], but many things start to go wrong.
I solved some of the problems but now I'm stuck.
C:\Windows\system32>python C:\Users\loren\Desktop\springer_free_books-master\main.py
Traceback (most recent call last):
File "C:\Users\loren\Desktop\springer_free_books-master\main.py", line 42, in <module>
books.to_excel(table_path)
File "C:\Users\loren\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\core\generic.py", line 2175, in to_excel
formatter.write(
File "C:\Users\loren\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\formats\excel.py", line 738, in write
writer.save()
File "C:\Users\loren\AppData\Local\Programs\Python\Python38-32\lib\site-packages\pandas\io\excel\_openpyxl.py", line 43, in save
return self.book.save(self.path)
File "C:\Users\loren\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\workbook\workbook.py", line 392, in save
save_workbook(self, filename)
File "C:\Users\loren\AppData\Local\Programs\Python\Python38-32\lib\site-packages\openpyxl\writer\excel.py", line 291, in save_workbook
archive = ZipFile(filename, 'w', ZIP_DEFLATED, allowZip64=True)
File "C:\Users\loren\AppData\Local\Programs\Python\Python38-32\lib\zipfile.py", line 1251, in __init__
self.fp = io.open(file, filemode)
FileNotFoundError: [Errno 2] No such file or directory: 'downloads\\table_v4.xlsx'
This is part of the code, were table_path is introduced.
table_url = 'https://resource-cms.springernature.com/springer-cms/rest/v1/content/17858272/data/v4'
table = 'table_' + table_url.split('/')[-1] + '.xlsx'
table_path = os.path.join(folder, table)
if not os.path.exists(table_path):
books = pd.read_excel(table_url)
# Save table
books.to_excel(table_path)
else:
books = pd.read_excel(table_path, index_col=0, header=0)
Try to create the destination directory before calling .to_excel() to ensure a valid writable directory exists. Make sure the os module is imported:
import os # add to your imports
and replace
books.to_excel(table_path)
with
os.makedirs(folder, exist_ok=True)
books.to_excel(table_path)
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.
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