1 #coding:utf-8 2 '''''cdays-4-exercise-6.py 文件基本操作 3 @note: 文件讀取寫入, 列表排序, 字符串操作 4 @see: 字符串各方法可參考hekp(str)或Python在線文檔http://docs.python.org/lib/string-methods.html 5 ''' 6 7 f = open('cdays-4-test.txt', 'r') #以讀方式打開文件 8 result = list() 9 for line in f.readlines(): #依次讀取每行 10 line = line.strip() #去掉每行頭尾空白 11 if not len(line) or line.startswith('#'): #判斷是否是空行或注釋行 12 continue #是的話,跳過不處理 13 result.append(line) #保存 14 result.sort() #排序結果 15 print result 16 open('cdays-4-result.txt', 'w').write('%s' % '\n'.join(result)) #保存入結果文件