Python,两次编写文件

时间:2015-11-20 14:05:45

标签: python python-3.x

我试图获取我的代码,因此它会更新Y7,Set1.txt,但它会继续在其中写入数据,+我添加的新数据。 我的代码如下:

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!")

然而,文本文件继续打印以前的值,+很多/////// 无论如何,我可以获取我的代码只是为了向该文件添加信息,而不添加所有的///和以前的名字?谢谢! 文件中发生的是:

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

1 个答案:

答案 0 :(得分:1)

使用"a"模式打开文件。仅需要读取文件时使用"r"模式,仅写入"w"(将擦除具有相同名称的现有文件)。

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

您可以查看docs