考生文件夹下存在一个文件PY101.py,请写代码替换横线,不修改其他代码,实现以下功能:
读取考生文件夹下的“poem.txt” 的内容,云除空行和注释行后,以行为单位进行排序,并将结果输出到
屏幕上。输出结果为:
A Grain of Sand
And a heaven in a wild flower,
And eternity in an hour,
Hold infinity in the palm of your hand,
To see a world in a grain of sand,
参考答案
f = open("poem.txt","r") result = [] for line in f: line = line.strip() if len(line) != 0 and line[0] != "#": result.append(line) result.sort()#排序 for line in result: print(line) f.close()