1. 程式人生 > 程式設計 >Python實現對word文件新增密碼去除密碼的示例程式碼

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,'')
    doc.SaveAs2(pt,None,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,tempname)
  def decryption(fp,key)
    doc.SaveAs2(pt,pw)
    doc.Close()
    word_app.Quit()
 
  decryption(path,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文件新增密碼去除密碼的示例程式碼的文章就介紹到這了,更多相關Python word文件新增密碼去除密碼內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!