Alejandro Trinchero
Alejandro Trinchero

Reputation: 93

Python beginner - Writing text file - problem: information doesn't save when opening with 'r+'

This is the last part of my project and I've been stuck for at least two weeks trying to figure out how to do it. Now I have this problem that: I create a text file to save information on each line (f.write(str(tobill) + '\n')) I already use this line on another parts and works perfectly. Now what is happening is that every time is supposed to save the info in a new line in the file. Instead of saving it is like overwriting the info that I already had in the file. So it never goes to a new line and save the new info, just overwrites the first line in the file.

elif action.lower() == 'bill' :
        p_b = input('Please insert number of table. \n -... ')
        with open (('T' + p_b)+ '.txt', 'r+') as p :
            tobill = 0
            for line in p : tobill = int(tobill) + int(line)

            xtra = input('Group table (+10 ppl)? y/n: \n')
            if xtra == 'y' :
                tobill = tobill + (tobill/100)*10
                print('SERVICE CHARGE ADDED.')

            elif xtra == 'n' : print ('Processing bill...')
            print('Total to pay:', tobill)
            print('Serviced by', user)

            #### Closing added part to bill.
            with open('closing.txt', 'w+') as f :
                f.write(str(tobill) + '\n')

# Closing days balance.
    elif action.lower() == 'closing' :
        result = 0
        with open('closing.txt', 'r+') as f :
            for line in f :
                result = int(result) + int(line)
            print(result)

This code above is the part where I have the problem.

Basically what I want to do is to: Write the output of 'Bill' in my program into the new text file 'closing', every time that I run 'Bill' this should add the total to 'closing'. This with the purpose that when the day finishes you could have a balance of all the tables created and billed.

Full code for better understanding:

#C
with open('names.txt', 'r') as r :
    f_n = r.read().splitlines()
print("Welcome to NAME.app")
##############
# USER LOGIN #
##############
while True:
    name = input("""
    \n - Insert name to logg in
    \n - ADD to save new user
    \n - LIST to see saved users
    \n - REMOVE to delete a user
    \n - EXIT to finish
    \n - ...""")

    lname = name.lower()

    if lname == "add":
        n_input = input("Name:")
        with open('names.txt', 'a') as f:
            f.write(n_input + '\n')

    elif lname == "list":
        with open('names.txt') as f:
            print(f.read().splitlines())
            f.close()

    elif name in f_n:
        print("Logged as", name.upper())
        user = name
        input('Welcome, press enter to continue \n')
        break

    elif lname == 'remove':
        rem = input("Insert user name to remove \n ...")
        with open('names.txt', 'r+') as f:
            l = f.readlines()
            l = [z for z in l if rem not in z]
        with open('names.txt', 'w') as f:
            f.writelines(l)

    elif lname == "exit":
        exit()
####################
# TABLE MANAGEMENT #
####################
#C:
while True:
    action = input ('''
 - NEW table
    \n - ADD table
    \n - BILL
    \n - CLOSING
    \n - EXIT
    \n - ... ''')

    d = {'(1) chburger': 19,'(2) bncburger': 23,'(3) plpasta': 6}

    if action == 'new' :
        tn = input('Insert table number \n - ...')
        name = 'T' + tn
        t = open(name + '.txt', 'w+')
        print('Done')

    elif action.lower() == 'add':

# Select table
        table = input ('Select desired table number: \n - ...')
        fulltab = 'T' + table
        with open(fulltab + '.txt', 'w+') as f :

# Order list and add Order
            while True:
                for k, v in d.items() :
                    print(k, v)
                addprod = input('Insert order. \n - ...')
                for k, v in d.items() :
                    if addprod == k[1] :
                        f.write(str(v) + '\n')

#Option to continue.
                q = input('Add more? y/n \n -...')
                if q.lower() == 'y' : continue
                if q.lower() == 'n' : break

 #File as F

    elif action.lower() == 'bill' :
        p_b = input('Please insert number of table. \n -... ')
        with open (('T' + p_b)+ '.txt', 'r+') as p :
            tobill = 0
            for line in p : tobill = int(tobill) + int(line)

            xtra = input('Group table (+10 ppl)? y/n: \n')
            if xtra == 'y' :
                tobill = tobill + (tobill/100)*10
                print('SERVICE CHARGE ADDED.')

            elif xtra == 'n' : print ('Processing bill...')
            print('Total to pay:', tobill)
            print('Serviced by', user)

            #### Closing added part to bill.
            with open('closing.txt', 'w+') as f :
                f.write(str(tobill) + '\n')

# Closing days balance.
#Closing added to bill line 95
    elif action.lower() == 'closing' :
        result = 0
        with open('closing.txt', 'r+') as f :
            for line in f :
                result = int(result) + int(line)
            print(result)

# Exit command.
    elif action.lower() == "exit":
        exit()

I know it's not the best, but it's my first project after studying and researching for 4 weeks.

Upvotes: 1

Views: 231

Answers (2)

איתן טורפז
איתן טורפז

Reputation: 132

ereldebel's answer is probably the way to go,
but if you're having problems you can always do it the hard and simple way,
by getting the text from the file and adding them together:

oldText = ''
with open('names.txt', 'r') as f:
oldText = f.read()
with open('names.txt', 'w') as f:
f.writelines(oldText + YourNewText)

Upvotes: 1

ereldebel
ereldebel

Reputation: 165

The problem is that you are using open with the argument 'r+' while what you want to use is 'a' or 'a+'.

opening a file in 'r+' will open file at the beginning and writing will overwrite lines instead of appending. that is why you should use 'a' or 'a+' as it writes new lines at the end of the file.

from: http://www.manpagez.com/man/3/fopen/

``r''   Open text file for reading.  The stream is positioned at the
             beginning of the file.

     ``r+''  Open for reading and writing.  The stream is positioned at the
             beginning of the file.

     ``w''   Truncate to zero length or create text file for writing.  The
             stream is positioned at the beginning of the file.

     ``w+''  Open for reading and writing.  The file is created if it does not
             exist, otherwise it is truncated.  The stream is positioned at
             the beginning of the file.

     ``a''   Open for writing.  The file is created if it does not exist.  The
             stream is positioned at the end of the file.  Subsequent writes
             to the file will always end up at the then current end of file,
             irrespective of any intervening fseek(3) or similar.

     ``a+''  Open for reading and writing.  The file is created if it does not
             exist.  The stream is positioned at the end of the file.  Subse-
             quent writes to the file will always end up at the then current
             end of file, irrespective of any intervening fseek(3) or similar.

Upvotes: 4

Related Questions