Home > OS >  Openpyxl : the load_workbook function was automatically called when the open function run
Openpyxl : the load_workbook function was automatically called when the open function run

Time:08-02

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 ?

CodePudding user response:

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.

  • Related