python close docx when a word file is in progress

created at 07-28-2021 views: 25

description

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/spider.py", line 252, in <module>
     os.remove(file_path)
PermissionError: [WinError 32] Another program is using this file and the process cannot access it. :'D:\\wordprss\\data\\1-copy (2).docx'

Solution

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)
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)
created at:07-28-2021
edited at: 07-28-2021: