0

For some reason this code acts like the edit mode isn't append:

def log_time(name, time):
    get_log(date.today())
    f = open(logFile, 'a')
    f.write(name + ' | ' + time + '\n')
    f.close()

Is there anything wrong with it just by looking at this function? I am reasonably sure that the other functions work fine. The problem is that when I call this function twice, only one thing shows up in the file.


I figured out what was wrong, but I don't know why it was wrong. When I created the file I used 'w+' mode and when I changed it to 'a' it worked. Can someone tell me why?

1 Answers1

1

'a' is the append mode. It will always put whatever you write at the end of the file (it won't write over it). I would also recommend using "with open" blocks instead of saying open and close each time you open a file.

def log_time(name, time):
    get_log(date.today())
    with open(logFile, 'a') as f:
        f.write(name + ' | ' + time + '\n')

It looks cleaner and it will close the file for you after the block. For more info on the modes you can see https://stackoverflow.com/a/1466036/13078162

Joshua Hall
  • 332
  • 4
  • 15