Hello, I am new to python and I am trying to do this task but it looks that I am missing some things which
is not visible to me can any body help me see those mistakes I am making and suggest how I should restracture
my code if needed? Any suggestion is helpful.
Thank you!
Task:
Also the other continuous project, the notebook, has relied on user actions in the sense that it would have broken down if the user had decided to read the file without writing anything to it. In this exercise we fix this, and add the possiblity of changing the used notebook file while the program is running.

First of all, make the program start by checking if there is a file "notebook.txt" and create one if there is none. If this has to be done, also inform the user with the warning "No default notebook was found, created one.".

When this feature works, add a fourth selection to the notebook, "(4) Change the notebook". If the user selects this option, the user is prompted for a new file "Give the name of the new file: ". If there is an existing file, it is opened and loaded into the notebook program, while the old notebook file is closed. If the new notebook file does not exist, the system informs the user "No notebook with that name detected, created one." and makes a new file. Also add a note of the used notebook file to the main menu, "Now using file [filename]". The best way to approach the required changes in this exercise is to first rewrite the code so that it stores the name of the used notebook file in a variable, and that this variable is changed as needed. Also, the easiest way of testing if a file exists is to open it to a file handle inside exception handler. If an IOError was generated, then there was no file with that name and write mode can be used to create such file. If everything is implemented correctly, the program works as follows:

>>> 

No default notebook was found, created one.

Now using file notebook.txt

(1) Read the notebook

(2) Add note

(3) Empty the notebook

(4) Change the notebook

(5) Quit



Please select one: 2

Write a new note: Buy milk.

Now using file notebook.txt

(1) Read the notebook

(2) Add note

(3) Empty the notebook

(4) Change the notebook

(5) Quit



Please select one: 4

Give the name of the new file: otherbook.txt

No notebook with that name detected, created one.

Now using file otherbook.txt

(1) Read the notebook

(2) Add note

(3) Empty the notebook

(4) Change the notebook

(5) Quit



Please select one: 2

Write a new note: Buy pineapples.

Now using file otherbook.txt

(1) Read the notebook

(2) Add note

(3) Empty the notebook

(4) Change the notebook

(5) Quit



Please select one: 4

Give the name of the new file: notebook.txt

Now using file notebook.txt

(1) Read the notebook

(2) Add note

(3) Empty the notebook

(4) Change the notebook

(5) Quit



Please select one: 1

Buy milk.:::12:05:23 04/25/11



Now using file notebook.txt

(1) Read the notebook

(2) Add note

(3) Empty the notebook

(4) Change the notebook

(5) Quit



Please select one: 5

Notebook shutting down, thank you.

>>> 

My code:

import time
try:
    f=open("notebook.txt")
    newf1= f.read()
    print("Now using file",newf1)
except IOError:
    print("No default notebook was found, created one.")
    mf=open("notebook.txt","w")
    newf2= mf.read()
    print("Now using file",newf2)
    filetext=newf2
promptForNumbers = True
while True:
    if promptForNumbers:
        print("(1) Read the notebook\n(2) Add note\n(3) Empty the notebook\n(4) Change the notebook\n(5) Quit\n")
        selection=int(input("Please select one: "))

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

        print(filetext)
        print("Now using file",filetext )
    elif selection==2:
        filetext=input("Write a new note: ")
        with open("notebook.txt", "a") as myfile:
            myfile.write(filetext)
            myfile.write(":::")
            myfile.write(time.strftime("%X %x"))
            print("Now using file",filetext )
    elif selection==3:
        readfile = open("notebook.txt","w")
        readfile.close()
        print("Notes deleted.")
    elif selection == 4:
        mf=input("Give the name of the new file: ")
        try:
            f=open(mf)
            filetext= f.read()
            print("Now using file",filetext)
        except IOError:
            print("No notebook with that name detected, created one.")
            mf=open(mf,"w")
            filetext= mf.read()
            print("Now using file",filetext )
            promptForNumbers = True
    elif selection==5:
        print("Notebook shutting down, thank you.")
        break
    else:
        print("Incorrect selection")

First thing I notice is line 9, where you write to new file for writing when file does not exist, even it is just created and can not have anything to read and secondly is opened for writing, not reading.

Hello sir, thank you for your time. So what I am trying to do on line 9 as you mentioned is that if the file notebook.txt doesn't exist it creates one. The program just checks this at first, that is why it is outside the while loop. Have you checked the the selection 4 where you change the notebook? It asks in the task to open the new file while the old file is closing. Am I doing it correct? Thanks!

You can not read from file opened for writing.

Perhaps your design spec's...

really does want you to copy each user input to a file
(append to a file) ...

right away after each line has been input?

The example 'dialog', you provided, does 'lend itself' to that simple interpretation ... yes/no ?

If that is what was 'expected',

this example may help:

# projectReadWriteNotebook2.py #

'''
    ... the other continuous project, the notebook, has relied on user actions 
    in the sense that it would have broken down if the user had decided to read
    the file without writing anything to it. In this exercise we fix this, and
    add the possiblity of changing the used notebook file while the program is 
    running.

    First of all, make the program start by checking if there is a file 
    "notebook.txt" and create one if there is none. If this has to be done, 
    also inform the user with the warning "No default notebook was found, 
    created one.".

    When this feature works, add a fourth selection to the notebook, 
    "(4) Change the notebook". If the user selects this option, 
    the user is prompted for a new file 
    "Give the name of the new file: ". 
    If there is an existing file, it is opened and loaded into the notebook 
    program, while the old notebook file is closed. If the new notebook file 
    does not exist, the system informs the user 
    "No notebook with that name detected, created one." 
    and makes a new file. Also add a note of the used notebook file to the 
    main menu, 
    "Now using file [filename]". 
    The best way to approach the required changes in this exercise is to first 
    rewrite the code so that it stores the name of the used notebook file in a 
    variable, and that this variable is changed as needed. 
    Also, the easiest way of testing if a file exists is to open it to a 
    file handle inside exception handler. If an IOError was generated, 
    then there was no file with that name and write mode can be used to 
    create such file. If everything is implemented correctly, 
    the program works as follows:


    No default notebook was found, created one.
    Now using file notebook.txt
    (1) Read the notebook
    (2) Add note
    (3) Empty the notebook
    (4) Change the notebook
    (5) Quit
    Please select one: 2
    Write a new note: Buy milk.
    Now using file notebook.txt
    (1) Read the notebook
    (2) Add note
    (3) Empty the notebook
    (4) Change the notebook
    (5) Quit
    Please select one: 4
    Give the name of the new file: otherbook.txt
    No notebook with that name detected, created one.
    Now using file otherbook.txt
    (1) Read the notebook
    (2) Add note
    (3) Empty the notebook
    (4) Change the notebook
    (5) Quit
    Please select one: 2
    Write a new note: Buy pineapples.
    Now using file otherbook.txt
    (1) Read the notebook
    (2) Add note
    (3) Empty the notebook
    (4) Change the notebook
    (5) Quit
    Please select one: 4
    Give the name of the new file: notebook.txt
    Now using file notebook.txt
    (1) Read the notebook
    (2) Add note
    (3) Empty the notebook
    (4) Change the notebook
    (5) Quit
    Please select one: 1
    Buy milk.:::12:05:23 04/25/11
    Now using file notebook.txt
    (1) Read the notebook
    (2) Add note
    (3) Empty the notebook
    (4) Change the notebook
    (5) Quit
    Please select one: 5
    Notebook shutting down, thank you.
'''



def readBook( fname ):
    #No default notebook was found, created one.
    #Now using file notebook.txt # note: print this in main ...#
    lineCount = 0
    try:
        with open( fname ) as fin:
            items = fin.readlines()
            for item in items:
                print( item.rstrip() )
                lineCount += 1
    except IOError:
        with open( fname, 'w' ) as fout:
            print( 'No default notebook was found, created one.' )
    return lineCount


def getDateTime():
    import datetime as dt
    return str(dt.datetime.now())[:-7]


def addNote( fname ):
    #Write a new note: Buy milk.
    text = input( 'Write a new note: ' )
    try:
        # note: append to *EXISTING* file ...
        with open( fname, 'a' ) as fin:
            fin.write( text + ':::' + getDateTime() + '\n' )      
    except IOError:
        print( 'Unexpected io error ...' )
        import sys
        sys.exit(1)

def empty( fname ):
    lineCount = readBook( fname )
    if lineCount:
        reply = input( 'Are you sure you want '
                       'to empty file {} (y/n) ? '.format( fname) )
        if reply in list('yY'):
            try:
                with open( fname, 'w' ) as fout:
                    print( fname, 'is now empty ...' )
            except IOError:
                print( 'Unexpected io error ...' )
                import sys
                sys.exit(1)
        else:
            print( 'Ok ... NOT emptied after all ...' )
    else:
        print( fname, 'is already empty!' )

def change():
    # Give the name of the new file: otherbook.txt
    # No notebook with that name detected, created one
    while( 1 ):
        new_fname = input( 'Enter the new file name like this (some_name.txt): ' )
        if len(new_fname) > 4 and new_fname[-4:] == '.txt' :
            break
        else:
            print( 'You must enter a valid "x.txt" file name ...' )
    try:
        with open( new_fname ) as fin:
            pass
    except IOError:
        with open( new_fname, 'w' ) as fout:
            print( 'No notebook with name {} found, '
                   'created one.'.format( new_fname ) )
    return new_fname


def main():
    # print( getDateTime() )
    MENU = \
'''(1) R ead the notebook
(2) A dd note
(3) E mpty the notebook
(4) C hange the notebook
(5) Q uit
Please select one: '''

    fname = 'notebook.txt'

    # ok ... now call ...
    readBook( fname )

    # then start main loop ...
    while True:
        print( '\nNow using file', fname )
        reply = input( MENU )
        print()
        if reply in list('1rR'): readBook( fname )
        elif reply in list('2aA'): addNote( fname )
        elif reply in list('3eE'): empty( fname )
        elif reply in list('4cC'): fname = change()
        elif reply in list('5qQ'): break

    print( 'Notebook shutting down, thank you.' )
    input( "Press 'Enter' to continue/exit ... " )


main()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.