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

python脚本实现文件夹增量复制

2016-03-09 16:24 603 查看
利用os包os.path.walk() 方法递归的遍历路径和文件

# -*- coding: utf-8 -*-
"""
Created on Tue Mar 08 10:29:52 2016
@author: Felix
"""
import os
import sys

def createIfNotExists(path):
if os.path.exists(path):
print "path already exists!"
else:
os.mkdir(path)
print "dir created"

def copy_file(src,tg):
if os.path.exists(tg):
print "path already exists!"
else:
os.system("cp %s %s"%(src,tg))
print "file created"

def check_dirs(src_dir,tg_dir):
for root,dirs,files in os.walk(src_dir):
for d in dirs:
src_dirname=os.path.join(root,d)
tg_dirname=src_dirname.replace(src_dir,tg_dir)
createIfNotExists(tg_dirname)
return True

def copy_all(src_dir,tg_dir):
for root,dirs,files in os.walk(src_dir):
for f in files:
src_filepath=os.path.join(root,f)
tg_filepath=src_filepath.replace(src_dir,tg_dir)
copy_file(src_filepath,tg_filepath)
return True

if __name__=='__main__':
src_dir= sys.argv[1]
tg_dir = sys.argv[2]
#    src_dir='D:/py/test'
#    tg_dir='D:/py/test2'
check_dirs(src_dir,tg_dir)
copy_all(src_dir,tg_dir)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: