1

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?

HuLu ViCa
  • 5,077
  • 10
  • 43
  • 93

2 Answers2

0

The mode r+ is read+write, but does not create the file if needed. I think you want w+. Nice table here.

Larry Lustig
  • 49,320
  • 14
  • 110
  • 160
  • Already said in the comment. – Matthieu Brucher Nov 27 '18 at 17:57
  • @MatthieuBrucher: Putting answers in comments defeats the purpose of StackOverflow. However, happy to remove my answer if you move your answer to the answer section. – Larry Lustig Nov 27 '18 at 18:01
  • Well, isn't your link basically saying this is a duplicate? So no need for any answer here. – Matthieu Brucher Nov 27 '18 at 18:02
  • No. While related, that question does not ask anything about the "open or create" functionality this user is looking for. One of the answers does contain a useful table, however. – Larry Lustig Nov 27 '18 at 18:05
  • That's your opinion. For me, and for lots of people, this is a duplicate, as OP wants to create a file. The fact that it's in a `with` clause doesn't change the original problem. – Matthieu Brucher Nov 27 '18 at 18:07
  • Without question I'm expressing only my opinion, sorry if I wasn't clear. At present, based on the number of close-as-duplicate votes, it appears one person only believes it's a duplicate. – Larry Lustig Nov 27 '18 at 18:12
  • Obviously, Python tag has a far lower barrier than stricter tags where this would already be closed. All depends on the number of questions I guess. – Matthieu Brucher Nov 27 '18 at 18:16
  • In your opinion, of course. . . – Larry Lustig Nov 27 '18 at 18:19
0

You can open the file in a+ mode (append mode with the permission to read) instead, and do a file seek to position 0 so that it creates the file if it doesn't already exist, but also allows reading the file from the beginning:

with open('ReservationsManagerApp/logs/'+data['booking']+'.json', 'a+') as outfile:
    outfile.seek(0)
blhsing
  • 91,368
  • 6
  • 71
  • 106