Python 文件添加列表数据后TypeError原因,pythontypeerror,# -*- coding


# -*- coding: utf-8 -*-#打开文件,将文件读入字符串col=''f=open('pride.txt')text=f.read()cols=text.split()f2=open('data.txt','w')for col in cols:    f2.write(col)    f2.write('\n')

以上代码运行无误。

# -*- coding: utf-8 -*-#打开文件,将文件读入字符串col=''f=open('pride.txt')text=f.read()cols=text.split().sort()f2=open('data.txt','w')for col in cols:    f2.write(col)    f2.write('\n')

对list进行排序后,进行写入,就出现了TypeError问题,虚心求解。

C:\Users\zhangning\Desktop\Python\learningPython\cases>python      stringTest.pyTraceback (most recent call last):  File "stringTest.py", line 8, in <module>    for col in cols:TypeError: 'NoneType' object is not iterable

你把 cols 打印出来看看?list.sort 和 sorted 是不同的哦。

问题在这里:

cols=text.split().sort()

list.sort() 的作用是对list内元素进行排序,不返回(返回None), 按照你的意图,应该是这样:

cols = text.split()cols.sort()

要不就是使用:

cols = sorted(text.split())

你看看sort()的返回值是什么!另外cols2从哪里冒出来的?

编橙之家文章,

评论关闭