繁体   English   中英

以只读二进制模式打开文件时无法在python中关闭文件

[英]Unable to close a file in python when opens it in read only binary mode

我正在使用 Python 3.9

基本上尝试根据以下链接中给出的公认答案使用代码来实现代码以获取文件的sha1->

在 Python 中生成多个文件的一个 MD5/SHA1 校验和

在这个链接上,在接受的答案中,一位专家提到 CLOSE 文件,但是在实现关闭文件的代码时,它不起作用并给出以下错误。 同样在接受的代码中无法通过 open 实现。

通过下面的编写代码,只是尝试检查使用 .read 以 rb 模式打开的文件是否实际上正在使用 close() 关闭,或者能够检查文件是否在 .read 后使用 .closed() 自动关闭。 两者都不起作用并且给出的错误与下面给出的相同。

        import os
        filename = r'/home/test/test.jar'
        fo = open(filename, 'rb').read()
        print(f'is closed {fo.closed}')

错误:- AttributeError: 'bytes' object has no attribute 'closed'

```python-BaseException```

请指教.....谢谢!

您可以使用with子句,完成后文件将自动关闭。 例如:

with open('text.json', 'rb') as f:
    ## this is a text file, for example
    text = f.read()
## file is closed automatically
print(text)
## text is printed out

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM