首页 > 解决方案 > 在 Python 中使用 smbclient 保存 Excel 文件

问题描述

在使用 openpyxl 执行一些工作簿操作后,我一直在尝试覆盖 Excel 文件。由于使用相关文件需要访问权限,因此正在使用 smbclient 来访问它。

尝试使用 openpyxl 对象的内置save()方法保存文件的新版本时会出现问题,根据文档,该save()方法涉及打开文件以完成操作:

>>> excel_file.save('\path\to\my\file.xlsx')

PermissionError: [Errno 13] Permission denied: '\path\to\my\file.xlsx'

由于文件受到限制,因此需要with在 smbclient 打开文件的块内执行操作。但是,这会导致抛出相同的错误,因为该save()方法无法再打开文件以完成操作,因为文件已经使用 smbclient 打开(文件被阻止):

with smbclient.open_file('\path\to\my\file.xlsx', mode='rb') as s:
    xlsx_file.save(s.name)
PermissionError: [Errno 13] Permission denied: '\path\to\my\file.xlsx'

在这里,s.name只是获取打开文件对象的路径属性。

有谁知道我如何解决这个问题?

标签: pythonopenpyxllibsmbclient

解决方案


我使用此连接,这对我有用:

with smbclient.open_file('\path\to\my\file.xlsx', mode='rb') as s
   xlsx_file.to_excel(s)

推荐阅读