'Writing to file JSON dump from Python 'with open' exception handling
I have one dataframe "students" that I am writing to a json file if and only if the weight column in calculated_df == 100, if it does not equal to 100, then it should write to the json file an "error."
try:
with open(input("Please enter an output path: "), 'w') as op:
json.dump({
'students': student_key['student'].to_list()
}, op, indent=2)
except:
for i, row in calculated_df.iterrows():
if row['weight'] != 100:
raise Exception json.dump({print("error:" "Invalid weight")},op)
Solution 1:[1]
I don't think you need to raise an exception. Your try statement is only valid for if the file cannot be written to (for example, permissions error)
Start with this
import json
filename = input("Please enter an output path: ")
data = {'students': student_key['student'].to_list()}
if 100 not in calculated_df['weight'].values: # replace with correct logic; don't need a loop to check all values
data = {"error": "Invalid weight"}
with open(filename, 'w') as op:
json.dump(data, op, indent=2)
Or if you did want to raise, then
with open(filename, 'w') as op:
json.dump(data, op, indent=2)
if 'error' in data:
raise Exception('An error occured')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
