python close docx when a word file is in progress

created at 07-28-2021 views: 25


After processing the word file, it needs to be deleted immediately. If os.revmoe() is used directly, the following error will be prompted:

Traceback (most recent call last):
   File "D:/wordprss/", line 252, in <module>
PermissionError: [WinError 32] Another program is using this file and the process cannot access it. :'D:\\wordprss\\data\\1-copy (2).docx'


python-docx can open documents from so-called file-like objects. It can also save to file-like objects. This may be convenient when you want to obtain source or target documents through a network connection or database, and do not want (or allow) to interact with the file system. In practice, this means that you can pass an open file or StringIO/BytesIO stream object to open or save the document as follows:

f = open('foobar.docx', 'rb')
document = Document(f)

# or

with open('foobar.docx', 'rb') as f:
    source_stream = StringIO(
document = Document(source_stream)
target_stream = StringIO()
created at:07-28-2021
edited at: 07-28-2021: