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

Question:

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:DownloadsTagUI_Windowstaguiflowssamples> 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:DownloadsTagUI_Windowstaguiflowssamplesexcel2.py", line 7, in <module>
    tagui_output = open('C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt','w')
  File "C:UsersxxxAppDataLocalProgramsPythonPython39libsite-packagesopenpyxlreaderexcel.py", line 316, in load_workbook
    reader = ExcelReader(filename, read_only, keep_vba,
  File "C:UsersxxxAppDataLocalProgramsPythonPython39libsite-packagesopenpyxlreaderexcel.py", line 124, in __init__
    self.archive = _validate_archive(fn)
  File "C:UsersxxxAppDataLocalProgramsPythonPython39libsite-packagesopenpyxlreaderexcel.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 ?

Asked By: conquer66666

||

Answers:

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.

Answered By: Azhar Khan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.