试图将输入插入到文件中,但具有“NoneType”对象是不可编辑的“错误”

2024-04-26 03:05:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从用户那里获取一个输入,并将该输入放在文件的正确位置。你知道吗

以下是我迄今为止所做的(名称.txt有一个按字母顺序排列的名字列表,我不想要任何重复的名字,所以我把列表转换成了一组)

def main():
    outfile = open("Names.txt","a")
    list1 = []
    name1 = 0
    name1 = input("Enter a name, if you want to quit, enter q: ")
    while name1 != "q":
        list1 = list1.append(name1)
        outfile.writelines(list1)
    list1.sort()
    s = set(list1)
    return s
main()

但是每当我输入q以外的东西时,我就会遇到问题

Traceback (most recent call last):
  File "C:\Users\SKKU\Desktop\1.py", line 12, in <module>
    main()
 File "C:\Users\SKKU\Desktop\1.py", line 8, in main
    outfile.writelines(list1)
TypeError: 'NoneType' object is not iterable

我该怎么办? 我做得对吗?你知道吗


Tags: inpytxt列表writelinesmainline名字
2条回答

向列表中添加名称的行应该是:

list1.append(name1)

因为append修改现有列表,并且不返回任何内容(即返回None)。你知道吗

因此,您使用list1 = list1.append(name1)list1设置为None。然后您将None传递给outfile.writelines,它试图迭代您传递的内容,当然,这对None没有意义。你知道吗

另一个指针,声明name1=0没有用

    name1 = 0   #you can remove this
    name1 = input("Enter a name, if you want to quit, enter q: ")
    while name1 != "q":
        list1 = list1.append(name1)
        outfile.writelines(list1)

另外,while循环正在无限期地向文件中写入行

您指示您的程序将name1附加到列表中,然后像@Blorgbeard所说的那样将一些没有意义的内容写入文件 因此,您可能需要在代码中重写/删除一些内容。你知道吗

您可能需要考虑读取一些列表操作(http://effbot.org/zone/python-list.htm)并使用for循环:

list = [#items]
for item in list: #instead of a while loop
#do something 
    print item

相关问题 更多 >