Closing a docx file if it's open

Question:

I’m working with docx files and to prevent the PermissionError: [Errno 13] Permission denied error, I tried to add os.close() in my code but as I saw, it doesn’t accept the file path, it accepts file descriptor as a parameter.So I tried that:

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

But when I run it, it passes the first PermissionError error because of the error handling, but when it tries to do fd = os.open(file_path, os.O_WRONLY), I got the same error. So is there a possible way to close a docx file if it’s open?

Edit:

Here is the entire traceback

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:Users17326PycharmProjectsnewEksimain2.py", line 194, in arat
    mydoc.save(dosya_yolu)
  File "C:Users17326PycharmProjectsnewEksivenvlibsite-packagesdocxdocument.py", line 167, in save
    self._part.save(path_or_stream)
  File "C:Users17326PycharmProjectsnewEksivenvlibsite-packagesdocxpartsdocument.py", line 111, in save
    self.package.save(path_or_stream)
  File "C:Users17326PycharmProjectsnewEksivenvlibsite-packagesdocxopcpackage.py", line 172, in save
    PackageWriter.write(pkg_file, self.rels, self.parts)
  File "C:Users17326PycharmProjectsnewEksivenvlibsite-packagesdocxopcpkgwriter.py", line 32, in write
    phys_writer = PhysPkgWriter(pkg_file)
  File "C:Users17326PycharmProjectsnewEksivenvlibsite-packagesdocxopcphys_pkg.py", line 141, in __init__
    self._zipf = ZipFile(pkg_file, 'w', compression=ZIP_DEFLATED)
  File "C:Users17326AppDataLocalProgramsPythonPython38-32libzipfile.py", line 1251, in __init__
    self.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'C:/Users/17326/Desktop/entries.docx'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:Users17326AppDataLocalProgramsPythonPython38-32libtkinter__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:Users17326PycharmProjectsnewEksimain2.py", line 197, in arat
    fd = os.open(dosya_yolu, os.O_WRONLY)
PermissionError: [Errno 13] Permission denied: 'C:/Users/17326/Desktop/entries.docx'
Asked By: Nurqm

||

Answers:

There is no such thing as an "open" file in python-docx. When you read in a file to edit it with document = Document("my-file.docx"), python-docx reads in the file and that’s it. Yes, it is open for a split second while it’s being read in, but it does not remain open. The open/close cycle ends before the Document() call returns.

Same when you’re saving the file. When you call document.save("my-output-file.docx"), the file is opened, written, and closed, all before the .save() method returns.

So it’s not like Word itself where you open a file, work on it for a while and then save and close it. You’re just reading a "starting" file into memory, making changes to that in-memory object, and then later writing the in-memory representation (almost always to a different file).

The comments are on the right track. Look for a permission problem not allowing you to write a file in that location that is not connected to an open file, unless you have the file in question open in Word or something at the time your program runs.

Answered By: scanny

python-docx can open a document from a so-called file-like object. It can also save to a file-like object. This can be handy when you want to get the source or target document over a network connection or from a database and don’t want to (or aren’t allowed to) interact with the file system. In practice this means you can pass an open file or StringIO/BytesIO stream object to open or save a document like so:

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)
Answered By: xin.chen

My attempt to add to others’ explanation, by showing some code.

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
Answered By: Aiden Zhao

Closing doc/docx file if its open using Python 1. Save the doc/docx file 2. Close the doc/docx file 3. Quit the Word Application

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()
Answered By: DS_ShraShetty
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.