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 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.