您好我的代码遇到了麻烦。当它写入文件时,文件中的文本会重复。当代码循环并添加更多文本时,它会加入已插入的文本。我想知道你是否可以帮助我阻止文本重复,但仍然写入新行。 我希望第一人称信息在第1行,第二人信息在第二行,依此类推,谢谢。
myFile1 = open("a-l.txt", "wt")
myFile2 = open("m-z.txt", "wt")
myList1 = ([])
myList2 = ([])
while 1:
surName = input("Enter your surname name:")
if surName[0] in ("A","B","C","D","E","F","G","H","I","J","K","L"):
myList1.append(surName)
title = input("Enter your prefered title:")
myList1.append(title)
firstName = input("Enter your first name:")
myList1.append(firstName)
bDay = input("Enter birthdate in mm/dd/yyyy format:")
myList1.append(bDay)
phoneNum = input("Enter your phone number:")
myList1.append(phoneNum)
email = input("Please enter your email.")
myList1.append(email)
for item in myList1:
myFile1.write(','.join(str(x) for x in myList1) + '\n')
elif surName[0] in ("M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"):
myList2.append(surName)
title = input("Enter your prefered title:")
myList2.append(title)
firstName = input("Enter your first name:")
myList2.append(firstName)
bDay = input("Enter birthdate in mm/dd/yyyy format:")
myList2.append(bDay)
phoneNum = input("Enter your phone number:")
myList2.append(phoneNum)
email = input("Please enter your email:")
myList2.append(email)
for item in myList2:
myFile2.write(','.join(str(x) for x in myList2) + '\n')
elif surName == "1":
break
myFile1.close()
myFile2.close()
答案 0 :(得分:2)
这是因为你实际上使用了两个for循环。您正在使用列表推导将整个列表连接到一行并将其写入文件,但您要执行X次,其中X是列表中的项目数。
for item in myList1:
myFile1.write(','.join(str(x) for x in myList1) + '\n')
您不需要外部for
循环
myFile1.write(','.join(str(x) for x in myList1) + '\n')