用python读取.txt文件内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为新的.txt文件

读取文件cdays-4-test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为cdays-4-result.txt。
cdays-4-test.txt文件内容如下:
#some wordsSometimes in life,You find a special friend;Someone who changes your life just by being part of it.Someone who makes you laugh until you can't stop;Someone who makes you believe that there really is good in the world.Someone who convinces you that there really is an unlocked door just waiting for you to open it.This is Forever Friendship.when you're down,and the world seems dark and empty,Your forever friend lifts you up in spirits and makes that dark and empty worldsuddenly seem bright and full.Your forever friend gets you through the hard times,the sad times,and the confused times.If you turn and walk away,Your forever friend follows,If you lose you way,Your forever friend guides you and cheers you on.Your forever friend holds your hand and tells you that everything is going to be okay.
==========
源代码如下:

运行结果有些出乎我的意料:

运行结果为什么这么混乱,完全不是按照顺序来的啊。我是python初学者,先谢谢各位了。

第1个回答  推荐于2017-12-15
a=open("cdays-4-test.txt","r")
_a=open("cdays-4-result.txt","w")
for b in a:
if b.startswith("#"):
continue
c=b.split()
if len(c)==0:
continue
else:
_a.write(b)
a.close()
_a.close()

你程序中间为啥要运行一次result.sort()呢?
你吧你的result.sort()去掉就正确了....你要求严格排序的话就不能去改顺序.....
你在那个result.sort()之前加一个print result 可以更好的看到在调用这个方法前后的不同之处......
我的那个是另一种写法 个人习惯写法问题...不用看 或者可以稍微了解一下处理过程...追问

这个程序是照书上的写的,我不明白result.sort()是以什么为排序标准的。

追答

sort()方法是对属性列表迳行一次原地排序,将原列表用进行了严格排序的新列表迳行替换掉 排序标准你可以认为成大小写敏感的排序方法 ,你可以把你的数据放到EXCEL裏 用A_Z排序的方式看看 这个排序标准和那个差不多。。。

追问

太感谢了

本回答被提问者和网友采纳