Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle close function when the file is opened successfully

I am trying to send file object in a rest call and want to receive its response but the POST method may throw some error and file will not be closed after that. So, I added close in except block also. But when I run the code the first api (GET) throws some error and in except it close the file which was never opened and throws another error. I don’t know how to handle the close() only when the file is opened.

Here is my Basic Structure of the code:

try:
    url = "some url"
    # This Response may throw some error
    response = requests.get(url = url, headers=headers,params=params)
    file = open("file.txt","r")
    # This Response may throw some error
    response = requests.post(url = url, headers=headers,params=params, files=file)
    file.close()
except:
    file.close()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use with statement in this situation. Using with means that the file will be closed as soon as you leave the block. This is beneficial because closing a file is something that can easily be forgotten and ties up resources that you no longer need. So, in this case you don’t have to specify file.close() anywhere as, with block will handle this internally.

Code

try:
    url = "some url"
    # This Response may throw some error
    response = requests.get(url = url, headers=headers,params=params)
    with open("file.txt","r") as file:
        # This Response may throw some error
        response = requests.post(url = url, headers=headers,params=params, files=file)
except Exception as exception:
    # Just Handle your exception here
    print(exception)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading