Home > Mobile >  how do i use try and else in function in python?
how do i use try and else in function in python?

Time:02-15

how do i request and export http file if to read 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 to my question

CodePudding user response:

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)
  • Related