4 回答
![?](http://img1.sycdn.imooc.com/54586431000103bb02200220-100-100.jpg)
TA贡献1752条经验 获得超4个赞
中不存在“打开”文件这样的东西python-docx
。当您读入文件并使用 进行编辑时document = Document("my-file.docx")
,python-docx
读入文件即可。是的,在读入时它会打开一瞬间,但不会保持打开状态。打开/关闭循环在Document()
调用返回之前结束。
保存文件时也是如此。当您调用 时document.save("my-output-file.docx")
,文件将被打开、写入和关闭,所有这些都在该.save()
方法返回之前进行。
因此,它与 Word 本身不同,您打开一个文件,处理一段时间,然后保存并关闭它。您只需将“起始”文件读入内存,对该内存中的对象进行更改,然后写入内存中的表示(几乎总是写入不同的文件)。
评论都在正确的轨道上。查找权限问题,不允许您在未连接到打开文件的位置写入文件,除非您在程序运行时在 Word 或其他内容中打开了相关文件。
![?](http://img1.sycdn.imooc.com/545845e900013e3e02200220-100-100.jpg)
TA贡献1936条经验 获得超6个赞
python-docx 可以从所谓的类文件对象打开文档。它还可以保存到类似文件的对象。当您想要通过网络连接或从数据库获取源或目标文档并且不想(或不允许)与文件系统交互时,这会很方便。实际上,这意味着您可以传递打开的文件或 StringIO/BytesIO 流对象来打开或保存文档,如下所示:
f = open('foobar.docx', 'rb')
document = Document(f)
f.close()
# or
with open('foobar.docx', 'rb') as f:
source_stream = StringIO(f.read())
document = Document(source_stream)
source_stream.close()
...
target_stream = StringIO()
document.save(target_stream)
![?](http://img1.sycdn.imooc.com/545862e700016daa02200220-100-100.jpg)
TA贡献1712条经验 获得超3个赞
我尝试通过显示一些代码来添加其他人的解释。
file_path = 'my file path'
mydoc = docx.Document()
mydoc.add_paragraph('text')
hasError = False
try:
fd = open(file_path)
fd.close()
mydoc.save(file_path)
except PermissionError:
raise Exception("oh no some other process is using the file or you don't have access to the file, try again when the other process has closed the file")
hasError = True
finally:
if not hasError:
mydoc.save(file_path)
return
![?](http://img1.sycdn.imooc.com/5458683f00017bab02200220-100-100.jpg)
TA贡献2019条经验 获得超9个赞
如果使用 Python 打开 doc/docx 文件,则关闭 该文件 1. 保存 doc/docx 文件 2. 关闭 doc/docx 文件 3. 退出 Word 应用程序
from win32com import client as wc
w = wc.Dispatch('Word.Application')
doc = w.Documents.Open(file_path)
doc.SaveAs("Savefilename_docx.docx", 16)
doc.Close()
w.Quit()
添加回答
举报