Home > front end >  How to handle close function when the file is opened successfully
How to handle close function when the file is opened successfully

Time:03-12

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()

CodePudding user response:

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)

CodePudding user response:

Your first problem is that you are relying within something in your try block happening. If your file doesn't exist, you'll get a different exception (and the exception catch will also fail). To remedy this, first check if your file variable exists at all:

if "file" in locals():

Now if it is, make sure it isn't already closed and close it if it is open.

    # ... within the if block
    if not file.closed:
        file.close()

Now you are free to handle your exception.

  • Related