自訂檔案夾處理函數(Python)

來源:互聯網
上載者:User

標籤:移動   覆蓋   目錄   合并   

#encoding: utf-8#author: walker#date: 2017-06-15#summary: 自訂檔案夾處理函數,適用於python3.5+import osimport shutilimport win32com.client#清空目錄def ClearDir(dir):    print(‘ClearDir ‘ + dir + ‘...‘)         for entry in os.scandir(dir):        if entry.name.startswith(‘.‘):            continue        if  entry.is_file():               os.remove(entry.path)    #刪除檔案        else:                              shutil.rmtree(entry.path)    #刪除目錄            #擷取目錄大小#不存在或空目錄都返回0def GetDirSize(pathdir):    if not os.path.exists(pathdir):        print(‘Warning: not exists %s‘ % pathdir)        return 0    fso = win32com.client.Dispatch(‘Scripting.FileSystemObject‘)    folder = fso.GetFolder(pathdir)     return folder.Size    ‘‘‘# 合并來源目錄到目標目錄,來源目錄中的空目錄不會被處理# src_dir: 來源目錄# dst_dir: 目標目錄# reserve_src: 是否保留來源資料# override: 是否覆蓋目標目錄中的檔案‘‘‘def MergeDir(src_root, dst_root, reserve_src=True, override=True):    if (not os.path.exists(src_root)) or (not os.path.exists(dst_root)):    #目錄不存在        raise FileNotFoundError    for parent, dirnames, filenames in os.walk(src_root):        for filename in filenames:            src_file = os.path.join(parent, filename)            dst_file = os.path.join(dst_root, src_file[len(src_root)+1:])            if os.path.exists(dst_file) and (not override):         #如果目標檔案存在且不能被覆蓋                continue            dst_dir = os.path.dirname(dst_file)            if not os.path.exists(dst_dir):                os.makedirs(dst_dir)            if reserve_src :     #保留來源資料                shutil.copyfile(src_file, dst_file)     #會覆蓋目標檔案            else:                shutil.move(src_file, dst_file)    if not reserve_src:        shutil.rmtree(src_root)     #刪除源根目錄


相關連結:

1、pywin32下載

2、Python檔案(夾)基本操作


*** walker ***


本文出自 “walker的流水賬” 部落格,請務必保留此出處http://walkerqt.blog.51cto.com/1310630/1936982

自訂檔案夾處理函數(Python)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.