代码之家  ›  专栏  ›  技术社区  ›  Marcos Placona

删除两个文件夹之间的差异

  •  0
  • Marcos Placona  · 技术社区  · 15 年前

    有谁能推荐一种方法(最好是ruby、python或dos)来只删除两个给定文件夹之间的不同文件和子文件夹吗?

    我不想安装任何东西,所以一个脚本将是伟大的。

    提前谢谢

    5 回复  |  直到 15 年前
        1
  •  0
  •   hughdbrown    15 年前

    当我想区分目录时,我就是这样做的:

    #!/usr/bin/env python
    
    import os, os.path
    import stat
    
    def traverse_path(start_dir='.'):
        for root, dirs, files in os.walk(start_dir, topdown=False):
            for f in files:
                complete_path = os.path.join(root, f)
                try:
                    m = os.stat(complete_path)[stat.ST_MODE]
                    if stat.S_ISREG(m):
                        yield complete_path[len(start_dir):]
                except OSError, err:
                    print 'Skipping', complete_path
                except IOError, err:
                    print 'Skipping', complete_path
    
    if __name__ == '__main__':
        s = set(traverse_path('/home/hughdbrown'))
        t = set(traverse_path('/home.backup/hughdbrown'))
        for e in s - t:
            print e
        print '-' * 25
        for e in t - s:
            print e
    

    注意,有一个常规文件检查。我似乎还记得,我遇到过用作信号量的文件,或者是由一个进程写入、由另一个进程或其他进程读取的文件。结果很重要。

    你可以根据你喜欢的规则添加代码来删除文件。

        2
  •  1
  •   luispedro    15 年前

        3
  •  0
  •   Mark Ransom    15 年前

    在Python中,可以使用 os.walk . 将每个完整路径名放入 set difference 方法获取不同的文件和文件夹。

        4
  •  0
  •   nmichaels    15 年前

    difflib 告诉你文件有什么不同 os.unlink 他们。实际上,如果您只需要知道文件是否完全不同,您只需将它们的文本与以下内容进行比较:

    for file1, file2 in files:
        f1 = open(file1, 'r').read()
        f1.close()
        f2 = open(file2, 'r').read()
        f2.close()
        if f1 != f2:
            os.unlink(file1)
            os.unlink(file2)
    

    你可以用 os.walk 获取文件列表。上面的代码没有新的东西 with

        5
  •  0
  •   ghostdog74    15 年前

    红宝石

    folder1=ARGV[0]
    folder2=ARGV[1]
    f1=Dir["#{folder1}/**"].inject([]){|r,f|r<<File.basename(f)}
    Dir["#{folder2}/**"].each{|f2|File.unlink(f2) if not f1.include?(File.basename(f2))}