如果我的目錄中不存在檔案,我如何請求和匯出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
感謝您花時間回答我的問題。
uj5u.com熱心網友回復:
代碼:
- 改用
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/424874.html
