Ross Wan's World!

Python, Ajax, PHP and Linux.

Posts Tagged ‘dircmp’

Syncfiles for Python 3: 文件夹同步

Posted by Ross Wan 于 2011/08/28

很久之前在 Python 2.5 下写了个同步两个文件夹的小脚本,  挺有用的, 方便了不少繁琐的资料同步操作, 成了每天必运行的小程序. 今天, 将其更新成兼容 Python 3. 其中有不少修改——之前主要是利用 os.listdir 遍历文件夹,利用 filecmp.dircmp 比较文件夹; 现在,依然用 filecmp.dircmp 来进行比较,但移除了 os.listdir, 因为后来发觉 filecmp.dircmp 来身就提供了 subdirs 方法遍历子文件夹, 而且更为便利, 修改后的脚本的行数也了少不少 :P

#!/bin/python
#coding=utf-8

import filecmp, shutil, os, sys

SRC = r'C:/a'
DEST = r'C:/b'

IGNORE = ['Thumbs.db']

def get_cmp_paths(dir_cmp, filenames):
    return ((os.path.join(dir_cmp.left, f), os.path.join(dir_cmp.right, f)) for f in filenames)

def sync(dir_cmp):
    print(dir_cmp.left)
    for f_left, f_right in get_cmp_paths(dir_cmp, dir_cmp.right_only):
        if os.path.isfile(f_right):
            os.remove(f_right)
        else:
            shutil.rmtree(f_right)
        print('删除 %s' % f_right)
    for f_left, f_right in get_cmp_paths(dir_cmp, dir_cmp.left_only+dir_cmp.diff_files):
        if os.path.isfile(f_left):
            shutil.copy2(f_left, f_right)
        else:
            shutil.copytree(f_left, f_right)
        print('复制 %s' % f_left)
    for sub_cmp_dir in dir_cmp.subdirs.values():
        sync(sub_cmp_dir)

def sync_files(src, dest, ignore=IGNORE):
    if os.path.isfile(src) or os.path.isfile(dest):
        print('只能对文件夹进行同步, 请正确输入源文件夹和目标文件夹...')
        return
    dir_cmp = filecmp.dircmp(src, dest, ignore=IGNORE)
    sync(dir_cmp)
    print('同步完成!')

if __name__ == '__main__':
    src, dest = SRC, DEST
    if len(sys.argv) == 3:
        src, dest = sys.argv[1:3]
    sync_files(src, dest)
    input()


脚本设置了默认的 src 和 dest 参数(源文件夹和目标文件夹), 也可以在运行脚本时指定:

python3 syncfiles_py3k.py your_src your_dest

Have fun~~

Posted in Python | Tagged: , , , , , | Leave a Comment »