简体   繁体   English

Openpyxl:当打开 function 运行时,会自动调用 load_workbook function

[英]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 output的代码如下

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?似乎 load_workbook function 在 open('C:/Downloads/TagUI_Windows/tagui/src/tagui_py/tagui_py.txt','w') function 运行时被自动调用,为什么会这样?

You've conflict for python io function open() with openpyxl.open .你有冲突 python io function open()openpyxl.open

from openpyxl import * is importing all functions which shadows built-in open() . from openpyxl import *正在导入所有隐藏内置open()的函数。 Restrict from openpyxl import s to limited function calls which you use. from openpyxl import您使用的有限 function 调用。

Also, use with open("path/tagui_py.txt", "w") as tagui_output: for better file-handling.此外,使用with open("path/tagui_py.txt", "w") as tagui_output:以获得更好的文件处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM