读取文件 cdays−4-test.txt 内容,去除空行和注释行后,以行为单位进行排序,并将
结果输出为 cdays−4-result.txt。
1 #!/usr/local/bin/python3
2 #-*- coding = utf-8 -*-
3 import os
4 import sys
5
6 oldfile = open("cdays-4-test.txt", "r") #以只读方式打开要求的文件
7
8 if os.path.exists("cdays-4-test.txt") == False: #判断该文件是否存在
9 >---print('no this file named cdays-4-test.txt')
10 return
11 newfile = open("cdays-4-result.txt", "w")
12
13 if os.path.exists("cdays-4-result.txt"):
14 >---print('this file has been creat,are you sure to change it?')
15 >---print('If you don \'t want that ,hit CTRL-C')
16 >---print('If you do want that, hit RETURN')
17
18 input("?") #询问是否继续
19
20 newfile.truncate() # 继续的话就清空该文件,这条命令慎用
21 result = list()
22 while True:
23 >---readbuff = oldfile.readline()
24 >---if readbuff == "": #判断是否读到文件末尾, readline 空行还有\n
25 >--->---break
26 >---
27 >---if readbuff == '\n' or readbuff.startswith('#'): #判断是否为空行或者注释行
28 >--->---continue
29 >---result.append(readbuff.strip("\n")) #去除每一行的\n,因为readline是把\n转成了字符串
30
31 result.sort() #字符串排序
32 #print(type(result))
33 for x in result:
34 >---newfile.write(str(x))
35 >---newfile.write('\n') #写入时加换行符,尽量保持源文件的格式
36
37 oldfile.close()
38 newfile.close()
39
40 print('cdays-4-result.txt has been created and changed')