检查文件完整性失败

2024-04-29 06:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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

所以当我运行文件名比较时,它无法匹配文件,因为它包含了整个文件路径。md5Srt是存储文件和校验和的dict。在

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

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"

Tags: 文件keyin路径目录文件名matchroot
1条回答
网友
1楼 · 发布于 2024-04-29 06:42:14

如果目录中只有一堆文件,则可以使用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目录,然后从每个路径的开头删除它们:

^{pr2}$

如果您将其与您的函数结合起来,您将得到:

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中找到一个md5sum与{}中的文件具有相同的md5sum。如果一个文件被重命名,或者有两个文件具有相同的哈希值,则可能会得到不完全相同的目录。更好的方法是先比较文件名,然后检查md5sums,如果src和{}中都有一个文件。在

以下是可能的情况:

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)

相关问题 更多 >