python写的目录同步小程序收藏

# -*- coding: utf-8 -*-
#目录同步工
#使用方法:
#SynchRoot sourcepath destinationpath
import os
import sys
import shutil
import getopt
#是否显示操作
_verbos = 0
#检查源目录的文件及文件夹
def SynchPath(src, dst):
    #如果目录不存在,则创建目录
    if not os.path.exists(dst):
        os.mkdir(dst)   
    names = os.listdir(src)
    for name in names:
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if os.path.isdir(srcname):    #目录
                #如果目录不存在,则创建目录
                if not os.path.exists(dstname):
                    os.mkdir(dstname)
                SynchPath(srcname, dstname)
            elif os.path.isfile(srcname):
                #查看目的目录下是否有这个文件,如果没有,则拷过去
                if not os.path.exists(dstname):
                    if _verbos == 1:
                        print "copying " + srcname + " to " + dstname
                    shutil.copy2(srcname, dstname)
        except (IOError, os.error), why:
            if _verbos == 1:
                print "Can't copy %s to %s: %s" % (`srcname`, `dstname`, str(why))
def usage():
    print '''
    usage: python SynchRoot.py -s srcpath -d dstpath -v
    sample: python SynchRoot.py -s E://重要 -d E://test
    '''
def Main(argv):
    srcpath = 'E://重要'
    dstpath = 'E://test'
    try:                               
        opts, args = getopt.getopt(argv, "hs:d:v", ["help", "source", "target", "verbos"])
    except getopt.GetoptError:         
        usage()                        
        sys.exit(2)
       
    for opt, arg in opts:
        if opt in ("-h", "--help"):     
            usage()                    
            sys.exit()                                  
        elif opt in ("-s", "--source"):
            srcpath = arg
        elif opt in ("-d", "--target"):
            dstpath = arg
        elif opt in ("-v", "--verbos"):               
            global _verbos              
            _verbos = 1
   
    if not os.path.exists(srcpath):
        print "错误:源路径必须存在!"
    else:
        print "正在同步: " + srcpath + " >>>>>>> " + dstpath
        SynchPath(srcpath, dstpath)
        print "已完成同步"
       

#执行操作
Main(sys.argv[1:])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值