2015-11-20 50 views
0

我試圖讓我的代碼更新Y7,Set1.txt,但它一直在寫數據,+我添加的新數據。 我下面的代碼:Python,將文件寫入兩次

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

公開賽"a"模式的文件。當只需要讀取文件時使用"r"模式,只有寫入時使用"w"(將刪除具有相同名稱的現有文件)。

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

您可以檢查docs