您的位置:首页 > 编程语言 > Python开发

python写的目录同步小程序

2009-01-30 14:20 453 查看
我需要定期将电脑的上的资料备份到移动硬盘,主要是一些照片,为了方便用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:])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: