在Python中解密后如何关闭MS Office文件?
我正在写一个函数来解密加密的word文件。我正在使用MSOffCrypto包。我想函数解密文件,如果它是加密的,并创建一个新的文件夹解密文件。我想让程序关闭文件并删除它。如果文件未加密,我希望程序将原始文件移动到与解密文件相同的文件夹中。以下是我到目前为止所写的内容:在Python中解密后如何关闭MS Office文件?,python,encryption,ms-word,Python,Encryption,Ms Word,我正在写一个函数来解密加密的word文件。我正在使用MSOffCrypto包。我想函数解密文件,如果它是加密的,并创建一个新的文件夹解密文件。我想让程序关闭文件并删除它。如果文件未加密,我希望程序将原始文件移动到与解密文件相同的文件夹中。以下是我到目前为止所写的内容: def DecryptFile(listdir): #Create a new directory for decrypted report files. #Decryption is necessary to s
def DecryptFile(listdir):
#Create a new directory for decrypted report files.
#Decryption is necessary to scrape embedded documents.
DecryptReportPath = dir + "\\ParentReportFiles\\"
os.mkdir(DecryptReportPath)
#Loop iterates through each file in the selected directory
for filename in listdir:
if (filename[-3:] == 'doc') | (filename[-4:] == 'docx'):
p = Path(filename)
PathParts = p.parts
try:
#Try to decrypt the MSOffice File.
try:
file = msoffcrypto.OfficeFile(open(filename, "rb"))
if file.is_encrypted():
# Use password
file.load_key(password="Viking1234!")
#Create the decrypted file in a new folder called ParentReportFiles
file.decrypt(open(DecryptReportPath + PathParts[-1][0:-5] + "decrypted.docx", "wb"))
file.close()
os.remove(filename)
else:
file.close()
os.rename(filename, DecryptReportPath+PathParts[-1])
except:
traceback.print_exc()
continue
except:
print("File is not doc")
问题是我收到以下错误消息:
Traceback (most recent call last):
File "C:/Users/.../Filing Master File 16 Dec 20.py", line 37, in DecryptFile
file.close()
AttributeError: 'OOXMLFile' object has no attribute 'close'
如果没有file.close()行,则会出现以下错误:
Traceback (most recent call last):
File "C:/Users/.../Filing Master File 16 Dec 20.py", line 38, in DecryptFile
os.remove(filename)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\...\\myfile.docx'
我尝试用os.close(文件)替换file.close(),但也不起作用:
Traceback (most recent call last):
File "C:/Users/.../Filing Master File 16 Dec 20.py", line 37, in DecryptFile
os.close(file)
TypeError: an integer is required (got type OOXMLFile)
请告知,非常感谢 我想问题就在这里
file = msoffcrypto.OfficeFile(open(filename, "rb"))
msoffcrypto.OfficeFile
不返回实现close()
方法的对象,但类型为OOXMLFile
的对象很可能是您希望关闭的对象是open(filename,“rb”)
操作的结果。所以我要尝试的是
org_file = open(filename, "rb")
file = msoffcrypti.OfficeFile(org_file)
...
org_file.close()
还请注意,您可以使用打开
操作作为一个简单的操作,而不必关心显式关闭文件。它将是:
with open(filename, "rb") as org_file:
file = msoffcrypti.OfficeFile(org_file)
...
os.remove(filename)
分别执行org_file=open(filename,“rb”),然后执行org_file.close()对我来说很有效。非常感谢你的帮助!