You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python加密校验脚本报FileNotFoundError但目标文件实际存在

问题排查与修复方案

错误根因

  • 路径拼接错误:os.listdir(dir_to_check) 仅返回目录下的文件名,不含父目录路径,直接将文件名传入open()时,Python会在脚本运行的当前工作目录查找文件,而非你指定的dir_to_check目录,因此触发文件不存在报错。
  • 变量名冲突:循环变量f是文件名,在with open(f, 'br') as f处被覆盖为文件对象,后续校验匹配后返回的是已关闭的文件对象,而非你需要的文件名。
  • 冗余操作:with上下文会自动管理文件句柄关闭,手动写f.close()属于多余操作。
  • 哈希算法不匹配:你的需求是匹配SHA512哈希值,但当前代码使用的是hashlib.sha256(),逻辑和需求不符。

修复后代码(已适配多哈希、单文件/目录场景)

#!/usr/bin/python3
import hashlib
import sys
import os

def calculate_file_hash(file_path, hash_algorithm='sha512', buf_size=65536):
    """通用文件哈希计算函数,支持自定义哈希算法"""
    if not hasattr(hashlib, hash_algorithm):
        raise ValueError(f"不支持的哈希算法:{hash_algorithm}")
    hash_obj = getattr(hashlib, hash_algorithm)()
    with open(file_path, 'rb') as f:
        while True:
            data = f.read(buf_size)
            if not data:
                break
            hash_obj.update(data)
    return hash_obj.hexdigest()

def main(to_check = sys.argv[1:]):
    if len(to_check) < 2:
        print("使用方法:脚本路径 <待检查目录/文件> <目标哈希值> [哈希算法,默认sha512]")
        sys.exit(1)
    target_path = to_check[0]
    target_hash = to_check[1]
    hash_alg = to_check[2] if len(to_check)>=3 else 'sha512'

    # 判断是单文件还是目录分别处理
    if os.path.isfile(target_path):
        file_hash = calculate_file_hash(target_path, hash_alg)
        if file_hash == target_hash:
            return target_path
    elif os.path.isdir(target_path):
        for filename in os.listdir(target_path):
            full_path = os.path.join(target_path, filename)
            # 跳过子目录仅处理文件
            if not os.path.isfile(full_path):
                continue
            file_hash = calculate_file_hash(full_path, hash_alg)
            if file_hash == target_hash:
                return full_path
    else:
        raise FileNotFoundError(f"指定的路径{target_path}不存在")
    return None

if __name__ == '__main__':
    match_file = main()
    print(match_file if match_file else "未找到匹配哈希的文件")

内容的提问来源于stack exchange,提问作者defarm

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 12:57:01