I am trying to modify existing excel file on Windows using Python via Pandas, but the program gives me an error.
This is a sample of my simple program:
df_read = pd.read_excel("C:\\Users\\77888\\Desktop\\HKR_ОТЧЕТЫ\\Ноябрь 2020\\2020-11-03.xlsx")
df = pd.DataFrame({"Время":[1], "Сумма счета":[1], "Столы":[1], "Заказ":[1]})
df = df.append({"Время":1, "Сумма счета":1, "Столы":1, "Заказ":1}, ignore_index = True)
path = "C:\\Users\\77888\\Desktop\\HKR_ОТЧЕТЫ\\Ноябрь 2020\\2020-11-03.xlsx"
assert os.path.isfile(path)
writer = pd.ExcelWriter(path, engine = 'xlsxwriter')
writer.save()
Here is the error:
Traceback (most recent call last):
File "C:\Users\77888\AppData\Local\Programs\Python\Python39\lib\site-packages\xlsxwriter\workbook.py", line 320, in close
self._store_workbook()
File "C:\Users\77888\AppData\Local\Programs\Python\Python39\lib\site-packages\xlsxwriter\workbook.py", line 638, in _store_workbook
raise e
File "C:\Users\77888\AppData\Local\Programs\Python\Python39\lib\site-packages\xlsxwriter\workbook.py", line 635, in _store_workbook
xlsx_file = ZipFile(self.filename, "w", compression=ZIP_DEFLATED,
File "C:\Users\77888\AppData\Local\Programs\Python\Python39\lib\zipfile.py", line 1239, in init
self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'C:\Users\77888\Desktop\HKR_ОТЧЕТЫ\Ноябрь 2020\2020-11-03.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\77888\Desktop\HKR_ОТЧЕТЫ\check.pu", line 12, in
writer.save()
File "C:\Users\77888\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\excel_xlsxwriter.py", line 193, in save
return self.book.close()
File "C:\Users\77888\AppData\Local\Programs\Python\Python39\lib\site-packages\xlsxwriter\workbook.py", line 322, in close
raise FileCreateError(e)
xlsxwriter.exceptions.FileCreateError: [Errno 13] Permission denied: 'C:\Users\77888\Desktop\HKR_ОТЧЕТЫ\Ноябрь 2020\2020-11-03.xlsx'
[Finished in 1.531s]
The most common cause of this issue on Windows is that the xlsx file being created is already open in Excel. For example:
# A simple pandas/xlsxwriter program.
C:\jmcnamara>type pandas_simple.py
import pandas as pd
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
writer.save()
# Run the program.
C:\jmcnamara>python pandas_simple.py
# Open the file in Excel.
C:\jmcnamara>pandas_simple.xlsx
# Try to rerun the program while the file is open.
C:\jmcnamara>python pandas_simple.py
Traceback (most recent call last):
File "C:\python\xlsxwriter\workbook.py", line 320, in close
File "C:\python\xlsxwriter\workbook.py", line 638, in _store_workbook
File "C:\python\xlsxwriter\workbook.py", line 636, in _store_workbook
File "C:\python\zipfile.py", line 1204, in __init__
self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'pandas_simple.xlsx'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "pandas_simple.py", line 8, in <module>
writer.save()
File "C:\python\site-packages\pandas\io\excel.py", line 1732, in save
return self.book.close()
File "C:\python\xlsxwriter\workbook.py", line 322, in close
xlsxwriter.exceptions.FileCreateError: [Errno 13] Permission denied: 'pandas_simple.xlsx'
As you can see the error is similar to yours.
This warning can also happen if you don't have write permissions for the output directory. That should be easy to check by trying to create a file in the target directory.
right click and run code with administrator permissions.
Through changing the privileges by running the programs you want use as "Run as administrator" for example I was using Excel in Pycharm so I changed to administrator privileges for both excel and Pycharm and got no error.
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 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 small application that I have made. It basically copies a zip file from a network location to the computer that is running the application, unzips it in a folder and then creates a shortcut on the desktop.
Most of the time (I'd say about 80%) it works as intended. The other 20% of the time the stack trace it says it cannot create a file. It is always the same (_bz2.pyd). If I close it and run it again it works fine after this happens.
Anyone have any ideas of what is going on? Here is the code that extracts the file. I've even made the script try and extract the file, check if it worked, try and extract the file again. This hasn't solved the issue:
print ('uncompressing databases. This takes a few minutes')
# file_name = settings.working_folder + r'\UAT_Databases.zip'
temp_name = settings_dict['working_folder'] + settings_dict['file_name']
zip_ref = zipfile.ZipFile(temp_name, 'r')
zip_ref.extractall(settings_dict['install_folder'])
zip_ref.close()
logr.info('unzipped databases')
Here is the stack trace:
Traceback (most recent call last):
File "temp_installer.py", line 141, in unzip_databases
File "zipfile.py", line 1347, in extractall
File "zipfile.py", line 1335, in extract
File "zipfile.py", line 1398, in _extract_member
PermissionError: [Errno 13] Permission denied: 'C:\\TempApps\\Temp_application\\_bz2.pyd'
2020-03-03 11:36:25,697 : ERROR : __main__ : could not unzip databases
Traceback (most recent call last):
File "temp_installer.py", line 141, in unzip_databases
File "zipfile.py", line 1347, in extractall
File "zipfile.py", line 1335, in extract
File "zipfile.py", line 1398, in _extract_member
PermissionError: [Errno 13] Permission denied: 'C:\\TempApps\\Temp_application\\_bz2.pyd'
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
This problem has been happening to me a lot lately.
When I run this code:
import xlwt
wb = xlwt.Workbook()
sheet = wb.add_sheet("Random")
sheet.write(0,0,"hello!")
wb.save("test.xls")
It gives me the error:
Traceback (most recent call last):
File "<module2>", line 16, in <module>
File "C:\Python27\lib\site-packages\xlwt\Workbook.py", line 662, in save
doc.save(filename, self.get_biff_data())
File "C:\Python27\lib\site-packages\xlwt\CompoundDoc.py", line 261, in save
f = open(file_name_or_filelike_obj, 'w+b')
IOError: [Errno 13] Permission denied: 'test.xls'
I've searched for the answer, but I couldn't find it.
Any help would be greatly appreciated!