我编写了一个简单的 Python 脚本来将文件从一个地方复制到另一个地方。(这是为了课堂,所以这就是为什么我不使用更简单的东西,比如shutil
。我在最后有一个比较两个文件的哈希值的检查,它始终告诉我它们是不同的,即使复制成功 -两者都是显示“hello world”的文本文件。
这是我的代码:
import os
def validity_checker(address1, dest_name):
try:
src = open(address1, 'rb')
dest = open(dest_name, 'wb+')
except IOError:
return False
return True
def copaste(address1, address2):
# concatenate address2 into filename
file_ending = address1.split('\\').pop()
dest_name = address2 + '\\' + file_ending
# copy file after calling checker
if validity_checker(address1, dest_name):
src = open(address1, 'rb')
dest = open(dest_name, 'wb+')
contents = src.read()
dest.write(contents)
src.close()
dest.close()
else:
print("File name bad. No action taken")
print src
print dest
print(hash(src)) #hash the file not the string
print(hash(dest))
return
和输出:
<closed file 'C:\\Users\\user\\Downloads\\hello.txt', mode 'rb' at 0x04B7D1D8>
<closed file 'C:\\Users\\user\\Downloads\\dest\\hello.txt', mode 'wb+' at 0x04C2B860>
-2042961099
4991878
加上文件被复制。
我相当确定哈希正在检查文件本身,而不是字符串。这可能与元数据有关吗?任何帮助将不胜感激。
您正在使用Python 特定的 hash()
函数,它计算用于字典键和set
内容的哈希值。
对于文件对象,hash()
基于对象标识;你不能以其他任何东西为基础,因为两个不同的文件对象永远不会相等,只有当两个对象在内存中是一个并且相同时,该fileobject.__eq__
方法才返回True
(is
也是如此)。文件内容、文件名、模式或任何其他对象属性在生成的哈希值中不起作用。
从功能文档:
返回对象的哈希值(如果有)。哈希值是整数。它们用于在字典查找期间快速比较字典键。
如果您需要验证文件副本是否包含相同的数据,则需要使用加密散列函数对 • 文件内容* 进行散列,这是完全不同的。使用hashlib
模块;对于您的用例,简单快速的MD5
算法将执行以下操作:
for closed_file in (src, dest):
with open(closed_file.name, 'rb') as reopened: # opened in binary mode!
print(reopened.name)
print(hashlib.md5(reopened.read()).hexdigest())
如果两个文件的二进制内容完全相同,那么它们的加密哈希值也将相同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句