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