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

Python 3.9中只读二进制模式打开文件无法关闭的问题求助

问题解决方案

错误原因分析

你写的测试代码里,open(filename, 'rb').read()执行后返回的是文件内容的字节对象(bytes),你把这个字节对象赋值给了fo,而不是文件句柄。字节对象本身没有closed属性,所以会触发AttributeError。

正确的文件状态检查与关闭方式

方式1:显式获取文件句柄并关闭

先拿到文件对象,再读取内容,最后手动关闭:

import os
filename = r'/home/test/test.jar'
fo = open(filename, 'rb')
content = fo.read()
print(f'is closed {fo.closed}')  # 此时输出False,文件未关闭
fo.close()
print(f'is closed {fo.closed}')  # 此时输出True,文件已关闭

方式2:使用with open上下文管理器(推荐)

with语句会自动在代码块结束后关闭文件,无需手动调用close(),是Python处理文件的最佳实践:

import os
filename = r'/home/test/test.jar'
with open(filename, 'rb') as fo:
    content = fo.read()
    print(f'is closed inside with: {fo.closed}')  # 输出False,文件在with块内保持打开
print(f'is closed outside with: {fo.closed}')  # 输出True,with块结束后文件自动关闭

适配多文件SHA1校验的with open写法

针对多文件SHA1校验需求,下面是用with open改写的代码,确保每个文件都被正确关闭:

import hashlib

def calculate_sha1_for_multiple_files(file_paths):
    sha1_hash = hashlib.sha1()
    
    for file_path in file_paths:
        # 用with open自动管理文件生命周期
        with open(file_path, 'rb') as f:
            # 分块读取大文件,避免内存占用过高
            chunk_size = 4096
            while chunk := f.read(chunk_size):
                sha1_hash.update(chunk)
    
    return sha1_hash.hexdigest()

# 示例调用
files_to_check = [r'/home/test/test.jar', r'/home/test/another_file.txt']
print(calculate_sha1_for_multiple_files(files_to_check))

代码说明

  • 使用with open打开每个文件,代码块结束后自动关闭文件,无需手动处理。
  • 采用分块读取(4096字节/块),避免一次性读取大文件导致内存溢出。
  • 逐个文件更新SHA1哈希对象,最终输出所有文件合并后的SHA1校验值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:24:26