如果您的目录中只有一堆文件,则可以使用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
与 .md5sum 中的文件相同的文件来比较文件src
。如果一个文件被重命名或者有两个文件具有相同的哈希值,你最终可能会得到不完全相同的目录。更好的方法是先比较文件名,然后检查 md5sums 是否有文件同时位于src
和dst
.
这可能是这样的:
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)