gpt4 book ai didi

python - 为什么我的代码在文件中多次重复

转载 作者:行者123 更新时间:2023-12-01 04:11:25 26 4
gpt4 key购买 nike

您好,我在使用这段代码时遇到了麻烦。当它写入文件时,文件中的文本会重复自身。当代码循环并添加更多文本时,它会连接到插入的文本。我想知道你是否可以帮助我停止重复文本,但仍然写入新行。我希望第一个人的信息位于第一行,第二个人的信息位于第二行,依此类推,谢谢。

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()

最佳答案

这是因为您实际上使用了两个 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')

关于python - 为什么我的代码在文件中多次重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34896039/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com