Home > OS >  Python notebook: Reading the note from a file
Python notebook: Reading the note from a file

Time:03-14

I am having trouble with one of my online coding exercises that I am trying to complete. The program does not read my note from the program as it should.

The exercise is simple, it wants me to add a code and then read it with time format and has other some menu options:

The last exercise in this chapter adds a small feature to the other continuous exercise project, the notebook. In this exercise, add a feature which includes the date and time of the written note to the program. The program works as earlier, but saves data in the form [note]:::[date and time] meaning that there is a three-colon separator between the note and timestamp. The timestamp can be generated as follows:

import time       
time.strftime("%X %x")
'19:01:34 01/03/09'

This returns the date and time in a nice, compact string. When working correctly, the program prints the following:

(1) Read the notebook.

(2) Add note.

(3) Empty the notebook.

(4) Quit

Please select one: 2.

Write a new note: Play football.

(1) Read the notebook.

(2) Add note.

(3) Empty the notebook.

(4) Quit.

Please select one: 1.

Play football:::21:11:24 11/04/11.

(1) Read the notebook.

(2) Add note.

(3) Empty the notebook.

(4) Quit.

Please select one: 4.

Notebook shutting down, thank you.

import time
    try:
        f=open("notebook.txt","r")
    
except Exception:
    mf=open("notebook.txt","w")
mf="notebook.txt"    
promptForNumbers = True
while True:
    if promptForNumbers:
        print("(1) Read the notebook\n(2) Add note\n(3) Empty the notebook\n(4) Quit\n")
        selection=int(input("Please select one: "))

if selection==1:
    handle = open(mf,"r")
    filetext = handle.read()

    print(filetext)
    
elif selection==2:
    filetext=input("Write a new note: ")

    myfile= open(mf, "w")
    myfile.write(filetext)
    myfile.write(":::")
    myfile.write(time.strftime("%X %x"))

elif selection==3:
    readfile = open(mf,"w")
    readfile.close()
    print("Notes deleted.")
    
elif selection == 4:
   
    print("Notebook shutting down, thank you.")
    break
else:
    print("Incorrect selection")

CodePudding user response:

You are missing myfile.close() after you finish writing to the file.

Ideally you should be closing the file after you finish operating on it (so it would be good to close handle.

Also, this might be bad formatting, but if your larger if is outside of while then you have to remove break in selection==4.

CodePudding user response:

It looks like you are opening the file multiple times and not closing it, which could cause problems. Use with to handle files instead, as this will close the file automatically at the end of the block. Use try...except block to test whether the file exists at the point where the user tries to access it, rather than doing this at the start of the program.

import time
# Remove these lines which open the file without closing it (were you testing whether the file exists?) 
#try:
#        f=open("notebook.txt","r")
#    
#except Exception:
#    mf=open("notebook.txt","w")
mf="notebook.txt"    
promptForNumbers = True
while True:
    if promptForNumbers:
        print("(1) Read the notebook\n(2) Add note\n(3) Empty the notebook\n(4) Quit\n")
        selection=int(input("Please select one: "))

    if selection==1:
        try:
            with open(mf) as f:
                print(filetext.read())
        except FileNotFoundError:
            print("The notebook file was not found")
    elif selection==2:
        text = input("Write a new note: ")
        with open(mf, "w") as f:
            f.write(text)
            f.write(":::")
            f.write(time.strftime("%X %x"))
    elif selection==3:
        with open(mf, "w") as f:
            pass
        print("Notes deleted.")   
    elif selection == 4:
        print("Notebook shutting down, thank you.")
        break
    else:
        print("Incorrect selection")

CodePudding user response:

From the first glance, your file handling is wrong.

    try:
        f=open("notebook.txt","r")
    
except Exception:
    mf=open("notebook.txt","w")

This thing really confuses me about why it is there, as you never use f anywhere, do not close it and if it raises an error you are opening the file as mf but you immediately lose the reference to it as you assign a filename to mf. You are opening the file multiple times, but rarely close it. The preferred way of opening a file in Python is using context manager like so:

with open(mf, "w") as myfile:
    myfile.write(filetext)
    myfile.write(":::")
    myfile.write(time.strftime("%X %x"))

This way when you exit the with block you are guaranteed to have your file closed.

  • Related