如何将文本保存为2个不同的文件?

时间:2016-01-20 13:27:57

标签: python

我目前正在攻读计算机科学的GCSE,我们的任务是让人们输入他们的姓氏,并根据姓氏中的第一个字母将其保存到两个不同的文件中。这两个文件是字母A-L(它们将用正确的第一个字母保存)但是另一个文本文件是M-Z,当键入该范围内的任何字母时,它似乎没有保存任何内容。如何根据他们的第一个字母将其保存到2个不同的文件中?

以下是我所拥有的:

    MyFile1 = open("A-L.txt", "wt")
    MyFile2 = open("M-Z.txt", "wt")
    myList = ([])

    Surname = input("What is your surname");
    if Surname[0] in ["A","B","C","D","E","F","G","H","I","J","K","L"]:
        myList.insert(2, Surname)
    for item in myList:
        MyFile1.write(item+"\n")
    if Surname[0] in ["M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]:
        MyFile2 = open("M-Z.txt", "wt")
        myList.insert(0, Surname)
    for item in myList:
    MyFile1.write(item+"\n")

2 个答案:

答案 0 :(得分:1)

没有所有列表业务:

MyFile1 = open("A-L.txt", "wt")
MyFile2 = open("M-Z.txt", "wt")

Surname = input("What is your surname");
if Surname[0] in ["A","B","C","D","E","F","G","H","I","J","K","L"]:
    MyFile1.write(Surname + "\n")
if Surname[0] in ["M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]:
    MyFile2.write(Surname + "\n")

答案 1 :(得分:0)

为什么不选择合适的文件名?

A_TO_L = set("ABCDEFGHIJKL")

surname = input("What is your surname? ")

if surname[0] in A_TO_L:
    fname = "A-L.txt"
else:
    fname = "M-Z.txt"

with open(fname, "wt") as outf:
    outf.write("\n".join(mylist))