Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Openpyxl : the load_workbook function was automatically called when the open function run

the code as below

from openpyxl import *
wb = load_workbook(r'./test.xlsx')
ws = wb.active
ws1 = wb.create_sheet("Mysheet")
ws.delete_cols(2)
wb.save('./test.xlsx')
tagui_output = open('C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt','w')
tagui_output.write(temp_result)
tagui_output.close()

the output of code as below

C:\Downloads\TagUI_Windows\tagui\flows\samples> python .\excel2.py
fn of load_workbook = ./test.xlsx
fn of load_workbook = C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt
Traceback (most recent call last):
  File "C:\Downloads\TagUI_Windows\tagui\flows\samples\excel2.py", line 7, in <module>
    tagui_output = open('C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt','w')
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 316, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "C:\Users\xxx\AppData\Local\Programs\Python\Python39\lib\site-packages\openpyxl\reader\excel.py", line 94, in _validate_archive
    raise InvalidFileException(msg)
openpyxl.utils.exceptions.InvalidFileException: filename=C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt openpyxl does not support .txt file format, please check you can open it with Excel first. Supported formats are: .xlsx,.xlsm,.xltx,.xltm

It seems the load_workbook function was automatically called when the open(‘C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt’,’w’) function run,why this happened ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’ve conflict for python io function open() with openpyxl.open.

from openpyxl import * is importing all functions which shadows built-in open(). Restrict from openpyxl imports to limited function calls which you use.

Also, use with open("path/tagui_py.txt", "w") as tagui_output: for better file-handling.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading