如果 docx 文件已打开,则将其关闭

我正在使用docx 文件并为了防止出现PermissionError: [Errno 13] Permission denied错误,我尝试添加os.close()代码,但正如我所见,它不接受文件路径,它接受文件描述符作为参数。所以我尝试了:


file_path = 'my file path'

mydoc = docx.Document()

mydoc.add_paragraph('text')

try:

    mydoc.save(file_path)

    return

except PermissionError:

    fd = os.open(file_path, os.O_WRONLY)

    os.close(fd)

    mydoc.save(file_path)

    return

PermissionError但是当我运行它时,由于错误处理,它会传递第一个错误,但是当它尝试执行时fd = os.open(file_path, os.O_WRONLY),我得到了相同的错误。那么,如果docx 文件已打开,是否有可能关闭它?


慕尼黑的夜晚无繁华
浏览 237回答 4
4回答

温温酱

中不存在“打开”文件这样的东西python-docx。当您读入文件并使用 进行编辑时document = Document("my-file.docx"),python-docx读入文件即可。是的,在读入时它会打开一瞬间,但不会保持打开状态。打开/关闭循环在Document()调用返回之前结束。保存文件时也是如此。当您调用 时document.save("my-output-file.docx"),文件将被打开、写入和关闭,所有这些都在该.save()方法返回之前进行。因此,它与 Word 本身不同,您打开一个文件,处理一段时间,然后保存并关闭它。您只需将“起始”文件读入内存,对该内存中的对象进行更改,然后写入内存中的表示(几乎总是写入不同的文件)。评论都在正确的轨道上。查找权限问题,不允许您在未连接到打开文件的位置写入文件,除非您在程序运行时在 Word 或其他内容中打开了相关文件。

LEATH

python-docx 可以从所谓的类文件对象打开文档。它还可以保存到类似文件的对象。当您想要通过网络连接或从数据库获取源或目标文档并且不想(或不允许)与文件系统交互时,这会很方便。实际上,这意味着您可以传递打开的文件或 StringIO/BytesIO 流对象来打开或保存文档,如下所示:f = open('foobar.docx', 'rb')document = Document(f)f.close()# orwith 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)

交互式爱情

我尝试通过显示一些代码来添加其他人的解释。file_path = 'my file path'mydoc = docx.Document()mydoc.add_paragraph('text')hasError = Falsetry:    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 = Truefinally:    if not hasError:        mydoc.save(file_path)return

慕少森

如果使用 Python 打开 doc/docx 文件,则关闭 该文件 1. 保存 doc/docx 文件 2. 关闭 doc/docx 文件 3. 退出 Word 应用程序from win32com import client as wcw = wc.Dispatch('Word.Application')doc = w.Documents.Open(file_path)doc.SaveAs("Savefilename_docx.docx", 16)doc.Close()w.Quit()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python