0

I am using Python 3.9

Basically trying to implement the code to get sha1 of file using code as per accepted answer given on below link ->

Generating one MD5/SHA1 checksum of multiple files in Python

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. Also in the accepted code not able to implement with 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(). 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'

```python-BaseException```

Please advice.....Thanks!

bsethi24
  • 45
  • 1
  • 8
  • yes fo.close() also throwing same error. and then tried to use fo.closed() to check whether this also working to check the file is getting automatically closed then its also giving this error. – bsethi24 Jul 23 '22 at 19:11
  • 4
    `fo` isn't the file object... it's the results of reading the file object... hence you get `bytes`... – Jon Clements Jul 23 '22 at 19:12
  • ok.... so any way to close the file or no its not require to close the file? However, the SME mentioned to close the file explicitly in his comment in the accepted answer of Generating one MD5/SHA1 checksum of multiple files in Python -> https://stackoverflow.com/questions/34807537/generating-one-md5-sha1-checksum-of-multiple-files-in-python/73093222#73093222 – bsethi24 Jul 23 '22 at 19:14
  • or below code requires to achieve this? `fo = open(filename, 'rb') abc = fo.read() print(f'is closed {fo.closed}') fo.close() print(f'is closed {fo.closed}')` and so how to generate SHA1 accepted code also , same change is required? `hash_obj = hashlib.sha1() for file in searched_file_list: print(f'{file}') try: file_for_sha1 = open(file, 'rb') hash_obj.update(file_for_sha1.read()) checksum = hash_obj.hexdigest() print(f'sha1 = {checksum}') finally: file_for_sha1.close()` – bsethi24 Jul 23 '22 at 19:20
  • Since the file is a temporary object and you don't retain any references to it, it should close on its own eventually. However it's better to intentional about it. – Mark Ransom Jul 23 '22 at 19:43
  • So, Mark the code in my above comment is correct or any better way? Please advice...Thanks! – bsethi24 Jul 23 '22 at 19:56

1 Answers1

2

You can use with clause and the file will be automatically closed when you're done with it. 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
Barry the Platipus
  • 9,594
  • 2
  • 6
  • 30