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
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 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.
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'
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!
I know you can open files, browsers, and URLs in the Python GUI. However, I don't know how to apply this to programs. For example, none of the below work. (The below are snippets from my growing chat bot program):
def browser():
print('OPENING FIREFOX...')
handle = webbroswer.get() # webbrowser is imported at the top of the file
handle.open('http://youtube.com')
handle.open_new_tab('http://google.com')
and
def file():
file = str(input('ENTER THE FILE\'S NAME AND EXTENSION:'))
action = open(file, 'r')
actionTwo = action.read()
print (actionTwo)
These errors occur, in respect to the above order, but in individual runs:
OPENING FIREFOX...
Traceback (most recent call last):
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 202, in <module>
askForQuestions()
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 64, in askForQuestions
browser()
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 38, in browser
handle = webbroswer.get()
NameError: global name 'webbroswer' is not defined
>>>
ENTER THE FILE'S NAME AND EXTENSION:file.txt
Traceback (most recent call last):
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 202, in <module>
askForQuestions()
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 66, in askForQuestions
file()
File "C:/Users/RCOMP/Desktop/Programming/Python Files/AI/COMPUTRON_01.py", line 51, in file
action = open(file, 'r')
IOError: [Errno 2] No such file or directory: 'file.txt'
>>>
Am I handling this wrong, or can I just not use open() and webbrowser in a program?
You should read the errors and try to understand them - they are very helpful in this case - as they often are:
The first one says NameError: global name 'webbroswer' is not defined.
You can see here that webbrowser is spelled wrong in the code. It also tells you the line it finds the error (line 38)
The second one IOError: [Errno 2] No such file or directory: 'file.txt' tells you that you're trying to open a file that doesn't exist. This does not work because you specified
action = open(file, 'r')
which means that you're trying to read a file. Python does not allow reading from a file that does not exist.