Python附加到.txt

时间:2018-04-28 20:09:29

标签: python append

嗨我还在学习python,目前正试图将一些数据写入txt文件。我在添加超过1个人的详细信息时遇到问题。我可以在第一个人的详细信息中工作正常但是当我选择添加其他人的详细信息时,我会收到以下错误。

line 58, in <module>
    datalist.append(first)
AttributeError: 'map' object has no attribute 'append'

任何帮助将不胜感激,我确实检查了其他类似的问题,但无法解决。

genderlist=["M", "F",]
moredata="Y"

datalist=[]
while (moredata=="Y" or moredata== "y"):

    datafile = open ("peSchool.text", "a+")
    first=input( "enter first name ")
    while not first.isalpha():
        print (" name should be alphabetic")
        first=input("enter first name ")
    second=input("surname ")
    while not second.isalpha():
        print (" surname should be alphabetic")
        second=input("enter surname ")
    postcode=input("postcode ")
    gender=input("enter gender ")
    gender=gender.upper()
    while gender not in genderlist:
        print ("gender should be M, F ")
        gender = input("Gender ")
        gender = gender.upper() 
    age=input("enter age ")
    while int(age) not in range(11,15):
        print(" age must be betwwen 11 and 15 ")
        age=input("enter age ")
    if int(age) ==11:
        group="1"
    elif int(age) ==12:
        group="2"
    elif int(age) ==13:
        group="3"
    else:
        group="4"


    unit=int(input("enter SATS units"))
    while int(unit) not in range(4,9):
        print(" SATS must be between 4 - 8 ")
        unit=input("enter SATS units")
    if int(unit) ==4:
        if gender=="M":
            unit = "Blake House"
        elif gender=="F":
            unit = "Woolfe House"
    elif int(unit) in range (5,6):
        if gender=="M":
            unit = "Harrison House"
        elif gender=="F":
            unit = "Gordon House"
    else:
        unit = "Jackson House"

    datalist.append(first)
    datalist.append(second)
    datalist.append(postcode)
    datalist.append(gender)
    datalist.append(age)
    datalist.append(unit)

    print (datalist.count)
    datalist = map(str, datalist)
    line = ",".join(datalist)
    datafile.writelines(line + "\n")





    print("First Name", first, "Surname", second, "Postcode", postcode, "Gender", gender, "Age", age, "house", unit, "Science Group ", group,)
    datafile.close()
    moredata=input("more students y/n ")
    moredata = moredata.upper()

1 个答案:

答案 0 :(得分:0)

这里有一些问题。

正如Patrick Haugh在上面指出的那样,map()会返回一个地图,而不是一个列表,因此没有.append()方法。您可以通过在列表中转换地图对象来解决此问题:datalist = list(map(str, datalist))

事实上,Python列表没有.count属性。相反,你可能想知道列表的长度,所以你可以print(len(datalist))

最后,存在一个逻辑错误:您需要在外部while循环结束时为每个学生写一行,或者收集所有收集的学生并立即写出来。前者更简单。只需将循环内的datalist变量清除到顶部,而不是在它之前。另请注意,由于您使用moredata = moredata.upper()和循环底部对案例进行规范化,因此您无需在顶部检查这两种情况。

while (moredata=="Y"):
    datalist=[]
...