简体   繁体   中英

Python, Writing the file twice

I'm trying to get my code so it will update Y7,Set1.txt but it keeps writing the data inside it again, + my new data that was added. My code below:

print("Registration System")
print("Make sure their is atleast one name in register!")
password = ("admin")
check = input("The Administration Password is: ")
if check == password:
    input("Enter any key to continue ")
    print("If their is no names in the register.txt\nThe script will stop working here!")
    set1 = list()
    set2 = list()
    set3 = list()
    set4 = list()
    set5 = list()
    with open("register.txt", "r") as register:
        registers = [line.rstrip("\n") for line in register]
        for pop in registers:
            print(pop)
            choice = input(
                'Where would you like it to go? (Enter 1 - set1, enter 2 - set2)')
            if choice == '1':
                set1.append(pop)
            elif choice == '2':
                set2.append(pop)
            elif choice == '3':
                set3.append(pop)
            elif choice == '4':
                set4.append(pop)
            elif choice == '5':
                set5.append(pop)
    with open("Y7,Set2.txt", "r") as Y7R:
        Y7 = [line.rstrip("\n") for line in Y7R]
        with open("Y7,Set2.txt", "w") as Y7Y:
            data = (str(Y7) + str(set2))
            Y7Y.writelines(data)
    with open("Y7,Set1.txt", "r") as d:
        Y7S = [line.rstrip("\n") for line in d]
        with open("Y7,Set1.txt", "w") as Y7D:
            data2 = str(Y7S) + str(set1)
            Y7D.writelines(data2)





else:
    print("Access Denied!")

However the text file keeps printing the previous values, + a lot of /////// Anyway I can get my code just to add information to that file, without adding all the /// and previous names? Thanks! What's happening in the file is:

['[\'[\\\'[\\\\\\\'[\\\\\\\\\\\\\\\'[\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'[\\\\\\\
PaulBrennan\\\\\\\\\

Open the file with "a" mode. "r" mode is used when the file only needs to be read and "w" for only writing (an existing file with the same name will be erased).

open("Y7,Set2.txt", "a")

You can check the docs .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM