使用xlwings访问.xlsb文件时出现WinError 123错误的解决问询
在使用xlwings开发Excel自动化程序时,能够正常访问.xlsx格式文件:
wb = xw.Book(r"some_directory\file1.xlsx")
但访问.xlsb格式文件时触发OSError: [WinError 123]错误,报错信息如下:
Input In [10], in <cell line: 1>()
----> 1 wb = xw.Book(r"some_directory\file2.xlsb")File ~\Anaconda3\lib\site-packages\xlwings\main.py:682, in Book.init(self, fullname, update_links, read_only, format, password, write_res_password, ignore_read_only_recommended, origin, delimiter, editable, notify, converter, add_to_mru, local, corrupt_load, impl)
680 if not app:
681 app = App(add_book=False)
---> 682 impl = app.books.open(fullname, update_links, read_only, format, password, write_res_password, ignore_read_only_recommended, origin, delimiter, editable, notify, converter, add_to_mru, local, corrupt_load).implFile ~\Anaconda3\lib\site-packages\xlwings\main.py:4278, in Books.open(self, fullname, update_links, read_only, format, password, write_res_password, ignore_read_only_recommended, origin, delimiter, editable, notify, converter, add_to_mru, local, corrupt_load)
4276 try:
4277 impl = self.impl(name)
---> 4278 if not os.path.samefile(impl.fullname, fullname):
4279 raise ValueError("Cannot open two workbooks named '%s', even if they are saved in different locations." % name)
4282 except KeyError:File ~\Anaconda3\lib\genericpath.py:100, in samefile(f1, f2)
94 def samefile(f1, f2):
95 """Test whether two pathnames reference the same actual file or directory
96
97 This is determined by the device number and i-node number and
98 raises an exception if an os.stat() call on either pathname fails.
99 """
---> 100 s1 = os.stat(f1)
101 s2 = os.stat(f2)
102 return samestat(s1, s2)OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'some_directory\file2.xlsb'
解决方法
- 改用正斜杠路径:将路径中的反斜杠替换为正斜杠,即使使用原始字符串前缀
r,正斜杠在Windows环境下也能被正确识别:wb = xw.Book(r"some_directory/file2.xlsb") - 用
os.path构建路径:借助Python标准库的os.path.join生成兼容路径,避免手动拼接路径的错误:import os file_path = os.path.join("some_directory", "file2.xlsb") wb = xw.Book(file_path) - 使用绝对路径:如果相对路径存在识别问题,直接使用文件的完整绝对路径:
wb = xw.Book(r"C:\full\path\to\some_directory\file2.xlsb") - 显式通过App实例打开:创建独立的Excel App实例后再打开文件,绕过
xw.Book直接初始化时的路径检查逻辑:app = xw.App(visible=False, add_book=False) wb = app.books.open(r"some_directory\file2.xlsb") - 检查路径合法性:确认文件路径中没有Windows禁止的特殊字符(如
:、*、?等),同时检查文件名和目录名是否存在拼写错误。
内容的提问来源于stack exchange,提问作者Tipo33

