python目录更新

新手上路,请多包涵
from subprocess import call
import os

def consistence(sourcedir, destinationdir):
    sr = set(os.listdir(sourcedir))
    de = set(os.listdir(destinationdir))

    os.chdir(sourcedir)

    for i in sr.difference(de):
        call(('rm', '-rf', i))

    for i in sr.intersection(de):
        if os.path.isdir(i):
            consist(sourcedir + '/' + i, destinationdir + '/' + i)

    for i in de.difference(sr):
        call(('cp', '-r', destinationdir + '/' + i, sourcedir))

我想将两个目录更新,但是两个目录下的相同目录就不行,不能更新共有目录下的文件

阅读 3.3k
1 个回答
✓ 已被采纳新手上路,请多包涵
#!/usr/bin/env python

from subprocess import call
import os
import sys

def consistency(sourcedir, destinationdir):
    sourcedir = unicode(sourcedir)
    destinationdir = unicode(destinationdir)

    sr = set(os.listdir(sourcedir))
    de = set(os.listdir(destinationdir))

    if not sr and not de:
        return

    os.chdir(sourcedir)

    for i in sr.difference(de):
        call(('rm', '-rf', i))

    for i in sr.intersection(de):
        if os.path.isdir(sourcedir + '/' + i) and os.path.isdir(destinationdir + '/' + i):
            consistency(sourcedir + '/' + i, destinationdir + '/' + i)

    for i in de.difference(sr):
        call(('cp', '-r', destinationdir + '/' + i, sourcedir))


def main():
    if len(sys.argv) > 3:
        print "Error: at most 3 arguments"
        print "Usage: consistency(source, destination)"
        return 1

    sourcedir = sys.argv[1]
    destinationdir = sys.argv[2]
    consistency(os.path.abspath(sourcedir), os.path.abspath(destinationdir))

if __name__ == '__main__':
    main()

搞掂

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题