md5.py 560 B

1234567891011121314151617
  1. import hashlib
  2. def md5_id(file_content_or_path):
  3. """计算文件内容或文件路径的MD5哈希值作为ID"""
  4. md5_hash = hashlib.md5()
  5. # 判断输入是文件内容(bytes)还是文件路径(str)
  6. if isinstance(file_content_or_path, bytes):
  7. # 直接处理文件内容
  8. md5_hash.update(file_content_or_path)
  9. else:
  10. # 处理文件路径
  11. with open(file_content_or_path, 'rb') as f:
  12. for chunk in iter(lambda: f.read(4096), b''):
  13. md5_hash.update(chunk)
  14. return md5_hash.hexdigest()