简体   繁体   English

当我只能以只读模式打开某些文件时,使用 Python comtypes 打开和保存 word 文件?

[英]Opening and Saving word files using Python comtypes when i can only open some files in read only mode?

Does anyone have any experience in opening many Word docs and saving them to PDF, but when they're on a shared server and it may be possible that someone else is editing them at the moment, but you still want to go through and save the PDF?有没有人有打开许多 Word 文档并将它们保存到 PDF 的经验,但是当它们在共享服务器上时,可能有其他人正在编辑它们,但你仍然想通过 go 并保存PDF?

I have some code using comtypes as follows, which works for files that aren't being edited by another user on the shared drive, but will fail if any of the docs are currently open by a coworker, as they open as read only and i cannot save.我有一些使用以下 comtypes 的代码,它适用于共享驱动器上其他用户未编辑的文件,但如果任何文档当前由同事打开,则会失败,因为它们以只读方式打开并且我无法保存。

word=comtypes.client.CreateObject(Word.Application)
word.Visible = 1
input_file_path = input_file_path
doc = word.Documents.Open(input_file_path)
file_name = os.path.splitext(input_file_name)[0]
output_file_path = output_file_path
doc.SaveAs(output_file_path,32)
doc.Close()
word.Quit()

open the word document as a data file, open a temporary word document as an output file, read data of BUFSIZE chunks in a loop, write the data to the output file, close files when complete.打开word文档为数据文件,打开临时word文档为output文件,循环读取BUFSIZE块数据,写入output文件,完成后关闭文件。 Basically, do a binary copy of the word file to a temporary file, then PDF-ize your resultant docx temporary file and remove it.基本上,将 word 文件的二进制副本复制到临时文件,然后 PDF 化生成的 docx 临时文件并将其删除。

It's an extra step and will require additional disk space for the temporary file, but if you aren't constrained it would certainly be safer than worrying about open files.这是一个额外的步骤,临时文件需要额外的磁盘空间,但如果你不受限制,它肯定比担心打开文件更安全。

This post: Python writing binary files, bytes offers some ideas on copying making copies of binary files.这篇文章: Python 编写二进制文件,字节提供了一些关于复制二进制文件副本的想法。

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

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