天天看點

python 檔案夾同步操作

作者:大肚皮程式猿
python 檔案夾同步操作

需求:

對檔案夾内(含多個子檔案夾)所有PDF、PPT、WORD檔案統計頁碼并更改檔案名複制到其它位置,要求檔案夾名相同

原檔案目錄:

python 檔案夾同步操作

代碼:

import os
#操作PDF
import pdfplumber
from pdfminer.pdfparser import PDFSyntaxError
#操作word
import pythoncom
from win32com import client
#操作PPT
from pptx import Presentation
#複制檔案
import shutil

path=os.getcwd()
file_path=os.path.join(path,"file")
output_path=os.path.join(path,"ouput")           
#擷取pdf文檔頁數
def get_pdf_page(pdf_path):
    try:
        f = pdfplumber.open(pdf_path)
        page = len(f.pages)
    except PDFSyntaxError:
        page = 0
   
    return page
           
#擷取word文檔頁數
def get_word_page(word_path):
    pythoncom.CoInitialize()
    # 調用word程式,不在前台顯示
    w = win32com.client.Dispatch("Word.Application")
    w.Visible = 0
    w.DisplayAlerts = 0
    # 打開一個word文檔
    doc = w.Documents.Open(word_path)
    # 擷取總頁數
    w.ActiveDocument.Repaginate()
    pages = w.ActiveDocument.ComputeStatistics(2)
    #print(pages)
    # 儲存并關閉
    #doc.SaveAs('test.docx')
    doc.Close()
    return pages           
#擷取ppt文檔頁數
def get_pptx_page(pptx_path):
    try:
        p = Presentation(pptx_path)
        page = len(p.slides)
    except KeyError:
        page = 0
    return page           
#多檔案夾同步
for i in os.walk("file") :
    #print(i)
    #同步檔案夾,如果沒有檔案夾将建立同名檔案夾
    if os.path.exists(output_path+"\\"+i[0])==False:
        os.mkdir(output_path+"\\"+i[0])
    if len(i[2])>0:
        for file in i[2]:
            f_name=file.split(".")
            #print(path+"\\"+i[0]+"\\"+file)
            if f_name[1]=="pdf":
                pdf_p=get_pdf_page(path+"\\"+i[0]+"\\"+file)
                print(path+"\\"+i[0]+"\\"+file+str(pdf_p))
                #複制檔案到輸出目錄
                shutil.copyfile(path+"\\"+i[0]+"\\"+file,output_path+"\\"+i[0]+"\\"+f_name[0]+"+"+str(pdf_p)+"頁.pdf")
            if f_name[1]=="docx":
                word_p=get_word_page(path+"\\"+i[0]+"\\"+file)
                print(path+"\\"+i[0]+"\\"+file+str(word_p))
                shutil.copyfile(path+"\\"+i[0]+"\\"+file,output_path+"\\"+i[0]+"\\"+f_name[0]+"+"+str(word_p)+"頁.docx")
            if f_name[1]=="pptx":
                ppt_p=get_pptx_page(path+"\\"+i[0]+"\\"+file)
                print(path+"\\"+i[0]+"\\"+file+str(ppt_p))
                shutil.copyfile(path+"\\"+i[0]+"\\"+file,output_path+"\\"+i[0]+"\\"+f_name[0]+"+"+str(ppt_p)+"頁.pptx")           

最終輸出:

python 檔案夾同步操作

如有自動化方面的需求請私信我,謝謝!