python中输出文本的指定行
1、输出文本的前三行
[root@PC1 test2]# ls a.txt test.py [root@PC1 test2]# cat a.txt ## 测试数据 1 u j d 2 s f f 3 z c e 4 z v k 5 c f y 6 w q r 7 a d g 8 e f s [root@PC1 test2]# cat test.py ## 程序 #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() for i in range(0, 3): out_file.write(lines[i]) in_file.close() out_file.close() [root@PC1 test2]# python test.py ##执行程序 [root@PC1 test2]# ls a.txt result.txt test.py [root@PC1 test2]# cat result.txt ##结果 1 u j d 2 s f f 3 z c e
2、输出文本的最后5行
001、
[root@PC1 test2]# ls a.txt test.py [root@PC1 test2]# cat a.txt 1 u j d 2 s f f 3 z c e 4 z v k 5 c f y 6 w q r 7 a d g 8 e f s [root@PC1 test2]# cat test.py #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() lines = lines[-5:] for i in lines: out_file.write(i) in_file.close() out_file.close() [root@PC1 test2]# python test.py [root@PC1 test2]# ls a.txt result.txt test.py [root@PC1 test2]# cat result.txt 4 z v k 5 c f y 6 w q r 7 a d g 8 e f s
002、
[root@PC1 test2]# ls a.txt test.py [root@PC1 test2]# cat a.txt 1 u j d 2 s f f 3 z c e 4 z v k 5 c f y 6 w q r 7 a d g 8 e f s [root@PC1 test2]# cat test.py #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() for i in range(len(lines) - 5, len(lines)): out_file.write(lines[i]) in_file.close() out_file.close() [root@PC1 test2]# python test.py [root@PC1 test2]# ls a.txt result.txt test.py [root@PC1 test2]# cat result.txt 4 z v k 5 c f y 6 w q r 7 a d g 8 e f s
3、提取偶数行或奇数行
[root@PC1 test2]# ls a.txt test.py [root@PC1 test2]# cat a.txt 1 u j d 2 s f f 3 z c e 4 z v k 5 c f y 6 w q r 7 a d g 8 e f s [root@PC1 test2]# cat test.py ## 程序 #!/usr/bin/python in_file = open("a.txt", "r") out_file1 = open("odd.txt", "w") out_file2 = open("even.txt", "w") lines = in_file.readlines() for i in range(0, len(lines)): if i % 2 == 0: out_file1.write(lines[i]) else: out_file2.write(lines[i]) in_file.close() out_file1.close() out_file2.close() [root@PC1 test2]# python test.py [root@PC1 test2]# ls a.txt even.txt odd.txt test.py [root@PC1 test2]# cat odd.txt 1 u j d 3 z c e 5 c f y 7 a d g [root@PC1 test2]# cat even.txt 2 s f f 4 z v k 6 w q r 8 e f s
4、提取不定行
[root@PC1 test2]# ls a.txt test.py [root@PC1 test2]# cat a.txt 1 u j d 2 s f f 3 z c e 4 z v k 5 c f y 6 w q r 7 a d g 8 e f s [root@PC1 test2]# cat test.py ## 提取2、3、5、7行 #!/usr/bin/python in_file = open("a.txt", "r") out_file = open("result.txt", "w") lines = in_file.readlines() num = [2, 3, 5, 7] for i in num: out_file.write(lines[i - 1]) in_file.close() out_file.close() [root@PC1 test2]# python test.py [root@PC1 test2]# ls a.txt result.txt test.py [root@PC1 test2]# cat result.txt ## 查看结果 2 s f f 3 z c e 5 c f y 7 a d g