Python 初学者 - 编写文本文件 - 问题:使用 'r+'

问题描述

这是我项目的最后一部分,我已经被困了至少两个星期,试图弄清楚如何去做。 现在我遇到了这个问题:我创建了一个 文本文件 来保存每一行 (f.write(str(tobill) + '\n')) 上的信息我已经在其他部分使用了这一行并且工作得很好。 现在发生的事情是每次都应该在文件新行保存信息。而不是保存它就像覆盖我已经在文件中的信息。所以它永远不会换行并保存新信息,只是覆盖文件中的第一行。

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)

上面这段代码是我遇到问题的部分。

基本上我想要做的是:将我程序中“比尔”的输出写入新的文本文件关闭”,每次运行“比尔”时,这应该将总数添加到“关闭”中。这样做的目的是当一天结束时,您可以拥有所有创建和计费的表的余额。

完整代码以便更好地理解:

#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','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()

我知道这不是最好的,但这是我学习和研究 4 周后的第一个项目。

解决方法

问题是您使用的是带有参数 'r+' 的 open 而您想要使用的是 'a' 或 'a+'。

在 'r+' 中打开文件将在开头打开文件,写入将覆盖行而不是追加。这就是为什么您应该使用 'a' 或 'a+' 的原因,因为它会在文件末尾写入新行。

来自: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.

,

ereldebel 的回答可能是要走的路,
但如果你遇到问题,你总是可以用困难而简单的方法来解决,
通过从文件中获取文本并将它们添加在一起:

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