[SOLVED] How do I use try and else in function in python?

Table of Contents

Issue

How do I request and export http file to read if file is not present in my directory?

My code :

def data():
  try:
    with open('sample.json', 'r') as openfile:  
      json_object = json.load(openfile)
  except FileNotFoundError as e:
    print(e)
  else:
    print('Downloading NOW...')
    url = 'https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json'
    d = requests.get(url).json()
    with open("sample.json", "w") as outfile:
      json.dump(d, outfile)
    print('sym  downloaded')
  finally:
    with open('sample.json', 'r') as openfile:  
      json_object = json.load(openfile)
    print(json_object)

What am i trying?

step 1 :   Try : Read file from directory
step 2 :   if file not found in directory than get it from url and export
step 3 :   than read again
step 4 :   if still erorr than print('Error in code Please Check')
           else print the read_file

Thank you for taking your time to response my question.

Solution

Code:

  • Use isfile(<file>) instead, it is a better option in this case.
  • isfile('sample.json') checks if file exists or not.
from os.path import isfile
def data():
  file='sample.json'
  if isfile(file):
    with open(file, 'r') as openfile:  
      json_object = json.load(openfile)
      
  else:
    print('Downloading NOW...')
    url = 'https://margincalculator.angelbroking.com/OpenAPI_File/files/OpenAPIScripMaster.json'
    d = requests.get(url).json()
    with open("sample.json", "w") as outfile:
      json.dump(d, outfile)
    print('sym  downloaded')

    with open('sample.json', 'r') as openfile:  
      json_object = json.load(openfile)

  print(json_object)

Answered By – Bibhav

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published.