Python實現對word文檔添加密碼去除密碼的示例代碼
更新時間:2020年12月29日 14:56:57 作者:1want0
這篇文章主要介紹了Python實現對word文檔添加密碼去除密碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
代碼實現如下:
import win32com.client,os,time def word_encryption(path, password): # 若加密保存.docx時,覆蓋原文件,則無法成功添加密碼。但是保存為另一個文件名,則可以添加密碼。 # 因此將A存為B,刪A,再將B改為A。 dirname, tempname = os.path.split(path) path_temp = os.path.join(dirname, tempname) while os.path.exists(path_temp): tempname = f'{len(tempname)}' + tempname path_temp = os.path.join(dirname, tempname) def encryption(fp, pt, pw): word_app = win32com.client.Dispatch('Word.Application') word_app.Visible = 0 word_app.DisplayAlerts = 0 doc = word_app.Documents.Open(fp, False, False, False, '') doc.SaveAs2(pt, None, False, pw) doc.Close() word_app.Quit() encryption(path, path_temp, password) os.remove(path) # 刪除原文件 os.rename(path_temp, path) # 改臨時文件名稱為原文件名稱 time.sleep(0.5) # 不要刪除,不要刪除 def word_decryption(path, password): # 若加密保存.docx時,覆蓋原文件,則無法成功添加密碼。但是保存為另一個文件名,則可以添加密碼。 # 因此將A存為B,刪A,再將B改為A。 dirname, tempname = os.path.split(path) path_temp = os.path.join(dirname, tempname) while os.path.exists(path_temp): tempname = f'{len(tempname)}' + tempname path_temp = os.path.join(dirname, tempname) def decryption(fp, pt, pw): word_app = win32com.client.Dispatch('Word.Application') word_app.Visible = 0 word_app.DisplayAlerts = 0 doc = word_app.Documents.Open(fp, False, False, False, key) doc.SaveAs2(pt, None, False, pw) doc.Close() word_app.Quit() decryption(path, path_temp, password) os.remove(path) # 刪除原文件 os.rename(path_temp, path) # 改臨時文件名稱為原文件名稱 time.sleep(0.5) # 不用刪除 def elistdir(path): for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path) and file_path==path:#排除子路徑 elistdir(file_path) #print(file_path) elif os.path.splitext(file_path)[1]=='.docx': #list_name.append(file_path) if file_path != '': print(file_path) try: word_encryption(file_path, key) except: pass def dlistdir(path): for file in os.listdir(path): file_path = os.path.join(path, file) if os.path.isdir(file_path) and file_path==path:#排除子路徑 dlistdir(file_path) #print(file_path) elif os.path.splitext(file_path)[1]=='.docx': #list_name.append(file_path) if file_path != '': print(file_path) try: word_decryption(file_path, '') except: pass if __name__ == '__main__': key='12345' #加密解密密匙 filedir=r"C:\Users\Administrator\Desktop"# 指定路徑不包含子路徑 elistdir(filedir) #遍歷word print('encrytion sucess\n Waiting...') time.sleep(2)#設置時間隨意操作 dlistdir(filedir) #遍歷word print('decrytion Done')
實現:
到此這篇關于Python實現對word文檔添加密碼去除密碼的示例代碼的文章就介紹到這了,更多相關Python word文檔添加密碼去除密碼內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
urllib和BeautifulSoup爬取維基百科的詞條簡單實例
這篇文章主要介紹了urllib和BeautifulSoup爬取維基百科的詞條簡單實例,具有一定借鑒價值,需要的朋友可以參考下2018-01-01
最新評論