You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用python-docx处理SharePoint文档时随机出现保存错误

问题:替换SharePoint文档链接时随机触发OSError: [Errno 22] Invalid argument

操作流程

  • 通过GraphAPI获取文档字节流,用上下文管理器写入本地文件
  • 解析docx文档提取所有超链接
  • 逐个匹配并替换目标链接,每替换一次就保存本地文档

错误现象

第三步操作时随机崩溃,抛出错误:OSError: [Errno 22] Invalid argument,且报错前已通过os.path.exists()验证文件路径存在。

相关日志及调用栈

Search for links to replace in D:\...\<filename>.docx 
Starting searching for and replacing links in <filename>.docx... 
path 'D:\...\<filename>.docx' exists: True 
Replaced hyperlink link 'https://docs.google.com/spreadsheets/d/<id>/edit#gid=590117954' with 'https://<domain>.sharepoint.com/sites/<name>/_layouts/15/Doc.aspx?sourcedoc=%...D&file=<file>' in paragraph #189. 
path 'D:\...\<filename>.docx' exists: True 
[Errno 22] Invalid argument: 'D:\\...\\<filename>.docx' 
Traceback (most recent call last):   
File "D:\...\sharepoint_links_replacer.py", line 156, in <module>
        raise e   File "D:\...\sharepoint_links_replacer.py", line 100, in <module>
        processed_links = update_file(matched_doc, in_doc_matched_links, site)   
File "D:\...\utils\sharepoint\sharepoint_mfa.py", line 487, in update_file
        replaced_links = update_doc(file_name, in_doc_links)   
File "D:\...\utils\editors.py", line 1160, in update_doc
        replaced_links = docx_replace(file_name, links_dicts)   
File "D:\...\utils\editors.py", line 818, in docx_replace
        doc.save(local_file_path)   
File "C:\Program Files\Python310\lib\site-packages\docx\document.py", line 154, in save
        self._part.save(path_or_stream)   
File "C:\Program Files\Python310\lib\site-packages\docx\parts\document.py", line 115, in save
        self.package.save(path_or_stream)   
File "C:\Program Files\Python310\lib\site-packages\docx\opc\package.py", line 174, in save
        PackageWriter.write(pkg_file, self.rels, self.parts)   
File "C:\Program Files\Python310\lib\site-packages\docx\opc\pkgwriter.py", line 32, in write
        phys_writer = PhysPkgWriter(pkg_file)   File "C:\Program Files\Python310\lib\site-packages\docx\opc\phys_pkg.py", line 141, in
    __init__
        self._zipf = ZipFile(pkg_file, 'w', compression=ZIP_DEFLATED)   
File "C:\Program Files\Python310\lib\zipfile.py", line 1249, in
    __init__
        self.fp = io.open(file, filemode) OSError: [Errno 22] Invalid argument: 'D:\\...\\<filename>.docx'

技术栈及补充信息

  • 使用Bayoo-docx v2.19(python-docx的分支版本,支持批注功能)
  • 无法提供完整最小复现示例,核心替换逻辑如下:
    1. 传入本地docx文件路径和待替换的链接字典
    2. 打开文档,遍历所有段落中的超链接
    3. 匹配到目标链接后替换其URL
    4. 调用doc.save()保存文档

内容的提问来源于stack exchange,提问作者Владислав Стадник

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 19:20:25