繁体   English   中英

Python附加到.txt

[英]Python append to a .txt

您好,即时通讯仍在学习python,目前正在尝试将一些数据写入txt文件。 我在添加多个人的详细信息时遇到问题。我可以使用第一个人的详细信息,但效果很好,但是当我选择添加其他人的详细信息集时,出现以下错误。

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

这里有些错误。

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

还有一个事实,就是Python列表没有.count属性。 相反,您可能想知道列表的长度,因此只需执行print(len(datalist))

最后,存在一个逻辑错误:您可能需要在外部while循环的末尾为每个学生写一行,或者收集所有收集的学生并立即将其写出。 前者要简单得多。 只需将循环内datalist变量的清除移到顶部,而不是移到顶部即可。 还要注意,由于您要使用moredata = moredata.upper()和循环的底部来规范化情况, moredata = moredata.upper()无需在顶部检查这两种情况。

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

暂无
暂无

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

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