无法检查文件完整性

时间:2012-10-25 10:44:49

标签: python python-2.7

我正在编写一个快速的Python脚本来将文件从一个目录迁移到另一个目录。一切都很完美,除了我必须比较文件名和校验和的部分。我将文件存储在两个位置,即/ root / src / file1和/ root / dst / file1。

因此,当我运行文件名比较时,它无法匹配文件,因为它包含整个文件路径。 md5Srt是一个存储文件和校验和的字典。

有没有办法可以在不使用整个文件路径的情况下比较文件名?

for key in md5Srt.keys():
    if key in md5Dst:
        print "keys match " + key
        print '\ncomparing the values of files\n'
        if md5Srt[key] == md5Dst[key]:
            print md5Srt[key]
            print md5Dst[key]
            print "files match\n"
            print "checking the next pair"
        else:
            print "values of files don't match"

1 个答案:

答案 0 :(得分:1)

如果您在目录中只有一堆文件,则可以使用os.path.basename

import os
>>> dst = os.path.basename('/root/dst/file1.file')
>>> src =  os.path.basename('/root/src/file1.file')
>>> dst
'file1.file'
>>> src
'file1.file'
>>> dst == src
True

如果您正在处理子目录,则需要知道基本src和dst目录,然后从每个路径的开头删除它们:

>>> src = '/root/src'
>>> dst = '/root/dst'
>>> src_file = '/root/src/dir1/file1.file'
>>> dst_file = '/root/dst/dir1/file1.file'
>>> os.path.relpath(src_file, src)
'dir1/file1.file'
>>> os.path.relpath(dst_file, dst)
'dir1/file1.file'
>>> os.path.relpath(src_file, src) == os.path.relpath(dst_file, dst)
True

如果你将它与你的功能结合起来,你会得到:

import os

src = '/root/src'
dst = '/root/dst'
for key, src_file in md5Srt.iteritems():
    dst_file = md5Dst.get(key)
    if dst_file is None:
        print 'The destination is missing %s' src_file
        continue

    print "keys match " + key
    print '\ncomparing the values of files\n'
    if  os.path.relpath(src_file, src) == os.path.relpath(dst_file, dst)
            print srcFile
            print dst_file
            print "files match\n"
            print "checking the next pair"
    else:
            print "values of files don't match"

我认为您应该重新考虑通过查找dst中与src中的文件具有相同md5sum的文件来比较文件。如果重命名文件或者有两个具有相同散列的文件,则最终可能会得到不完全相同的目录。更好的方法是首先比较文件名,然后检查md5sums是否存在同时包含srcdst的文件。

这可能是这样的:

import os

src_dir = '/root/src'
dst_dir = '/root/dst'

# reverse the dictionaries, hopefully you would create these dictionaries 
# to begin with. A single file can only have one md5sum, but the same md5Sum can 
# match multiple files
src_file_hashes = dict((os.path.relpath(v, src_dir), k) for k, v in md5Srt)
dst_file_hashes = dict((os.path.relpath(v, dst_dir), k) for k, v in md5Dst)

for src_file, src_hash in src_file_hashes.iteritems():
    dst_hash = dst_file_hashes.get(src_file)

    src_path = os.path.join(src_dir, src_file)
    dst_path = os.path.join(dst_dir, dst_file)

    if dst_hash is None:
        print 'The destination file %s is missing ' % dst_path
        continue

    if  src_hash == dst_hash:
        print '%s matches %s and %s' % (src_hash, src_path, dst_path)
    else:
        print '%s and %s have different hashes' % (src_path, dst_path)