简体   繁体   English

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

[英]Why does my code repeat itself more than once in a file

Hello i am getting trouble with this code. 您好,我在使用此代码时遇到麻烦。 When it writes to a file the text within the file repeats itself. 当它写入文件时,文件中的文本会重复。 When the code loops and more text is added it join on the text that was inserted. 当代码循环并添加更多文本时,它将加入所插入的文本。 I was wondering if you could help me stop the text repeating itself but still write to a new line. 我想知道您是否可以帮助我停止重复的文本,但仍然写到新行。 I want the 1st persons information to be on a 1 line and the second persons information to be on the second line and so on,Thanks you. 我希望第一人称信息在第一行,第二人称信息在第二行,依此类推,谢谢。

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

It's because you're actually using two for loops. 这是因为您实际上使用了两个for循环。 You're using a list comprehension to join the whole list into a single line and write it to the file, but you're doing that X times, where X is the number of items in the list. 您正在使用列表推导将整个列表合并为一行并将其写入文件,但是您执行了X次,其中X是列表中的项目数。

for item in myList1:
     myFile1.write(','.join(str(x) for x in myList1) + '\n')

You don't need the outer for loop 您不需要外部for循环

myFile1.write(','.join(str(x) for x in myList1) + '\n')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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