Python,将list写入文件出现TypeError
黄舟
黄舟 2017-04-17 11:36:20
[Python讨论组]
# -*- 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
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

全部回复(3)
ringa_lee

问题在这里:

cols=text.split().sort()

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

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

要不就是使用:

cols = sorted(text.split())
高洛峰

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

伊谢尔伦

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号