如何在 python 的函数中使用 try 和 else?

How do I use try and else in function in python?

如果文件不在我的目录中,我该如何请求和导出要读取的 http 文件?

我的代码:

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)

我在尝试什么?

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

感谢您花时间回答我的问题。

代码:

  • 改用isfile(<file>),在这种情况下这是更好的选择。
  • isfile('sample.json') 检查文件是否存在。
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)