I have the following code, but it doesn't work if the file doesn't exist:
def log(self, action, data):
import json
with open('ReservationsManagerApp/logs/'+data['booking']+'.json', 'r+') as outfile:
log_data = {
'timestamp': str(datetime.today()),
'action': action,
'data': data
}
json.dump(log_data, outfile)
I want the method to create the file if it doesn't exist, but all the examples I have found don't explain how to do it using with
clause, they just use try: open
.
How can I instruct with
clause to create the file if it doesn't exist?