码迷,mamicode.com
首页 > 编程语言 > 详细

自定义文件夹处理函数(Python)

时间:2017-06-15 16:30:19      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:移动   覆盖   目录   合并   

#encoding: utf-8
#author: walker
#date: 2017-06-15
#summary: 自定义文件夹处理函数,适用于python3.5+

import os
import shutil
import 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)    #删除目录
            
#获取目录大小
#不存在或空目录都返回0
def 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)

标签:移动   覆盖   目录   合并   

原文地址:http://walkerqt.blog.51cto.com/1310630/1936982

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!