# -*- 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.py
Traceback (most recent call last):
File "stringTest.py", line 8, in <module>
for col in cols:
TypeError: 'NoneType' object is not iterable
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
问题在这里:
list.sort() 的作用是对list内元素进行排序,不返回(返回None), 按照你的意图,应该是这样:
要不就是使用:
你看看sort()的返回值是什么!另外cols2从哪里冒出来的?
你把
cols
打印出来看看?list.sort
和sorted
是不同的哦。