简体   繁体   English

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

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

I am using Python 3.9我正在使用 Python 3.9

Basically trying to implement the code to get sha1 of file using code as per accepted answer given on below link ->基本上尝试根据以下链接中给出的公认答案使用代码来实现代码以获取文件的sha1->

Generating one MD5/SHA1 checksum of multiple files in Python 在 Python 中生成多个文件的一个 MD5/SHA1 校验和

on this link also, in accepted answer, one of expert mention to CLOSE the file but when implementing the code to close the file, its not working and giving below error.在这个链接上,在接受的答案中,一位专家提到 CLOSE 文件,但是在实现关闭文件的代码时,它不起作用并给出以下错误。 Also in the accepted code not able to implement with open.同样在接受的代码中无法通过 open 实现。

And by below written code, just tried to check whether file opened in rb mode with .read is actually getting closed using close() or able to check whether file is automatically closed after .read using .closed().通过下面的编写代码,只是尝试检查使用 .read 以 rb 模式打开的文件是否实际上正在使用 close() 关闭,或者能够检查文件是否在 .read 后使用 .closed() 自动关闭。 both not working and giving error same as given below.两者都不起作用并且给出的错误与下面给出的相同。

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

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

```python-BaseException```

Please advice.....Thanks!请指教.....谢谢!

You can use with clause and the file will be automatically closed when you're done with it.您可以使用with子句,完成后文件将自动关闭。 For example:例如:

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