1. 程式人生 > 其它 >python中輸出文字的指定行

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