python:關於讀取文件的指定行的問題

先來造一個文件:就叫作 test.txt吧,內容是下面這個樣子:python

表頭
1,數據1
2,數據2
3,數據3
4,數據4
5,數據5
6,數據6
7,數據7

那麼咱們並不打算把這個表頭給讀出來spa

怎麼辦呢?code

先來打開文件:索引

fileName = 'test.txt'
with open(fileName,'r',encoding='UTF-8') as f:
    lines = f.readlines()
    print(str(type(lines))+'\n'+str(lines))

獲得下面的結果:ip

<class 'list'>
['表頭\n', '1,數據1\n', '2,數據2\n', '3,數據3\n', '4,數據4\n', '5,數據5\n', '6,數據6\n', '7,數據7\n']
Process finished with exit code 0

那麼 f.readlines()返回的是一個列表.每一項是一行it

這就好辦了,由於列表是能夠切片的嘛class

fileName = 'test.txt'
with open(fileName,'r',encoding='UTF-8') as f:
    lines = f.readlines()
    print(str(type(lines))+'\n'+str(lines))
    for i in lines[1:6]:
        print(i.strip('\n'))

這樣一切片,就能獲得須要的結果了:test

<class 'list'>
['表頭\n', '1,數據1\n', '2,數據2\n', '3,數據3\n', '4,數據4\n', '5,數據5\n', '6,數據6\n', '7,數據7\n']
1,數據1
2,數據2
3,數據3
4,數據4
5,數據5

Process finished with exit code 0

那麼若是我想要隔一行讀一行呢?coding

很簡單,使用列表切片的步長就好了:file

fileName = 'test.txt'
with open(fileName,'r',encoding='UTF-8') as f:
    lines = f.readlines()
    print(str(type(lines))+'\n'+str(lines))
    for i in lines[1:6:2]:
        print(i.strip('\n'))
<class 'list'>
['表頭\n', '1,數據1\n', '2,數據2\n', '3,數據3\n', '4,數據4\n', '5,數據5\n', '6,數據6\n', '7,數據7\n']
1,數據1
3,數據3
5,數據5

Process finished with exit code 0

那麼我再搞一下,每次輸出的結果的行號是個斐波那契數列...也就是輸出 1,1,2,3,5,8行這樣,要怎麼辦呢?

def gap(maxtcl):
    n,a,b=0,0,1
    while n<maxtcl:
        yield b
        a,b=b,a+b
        n=n+1

fileName = 'test.txt'
with open(fileName,'r',encoding='UTF-8') as f:
    lines = f.readlines()
    print(str(type(lines))+'\n'+str(lines))

for i in gap(5):
    print(lines[i])

結果:

<class 'list'>
['表頭\n', '1,數據1\n', '2,數據2\n', '3,數據3\n', '4,數據4\n', '5,數據5\n', '6,數據6\n', '7,數據7\n']
1,數據1

1,數據1

2,數據2

3,數據3

5,數據5


Process finished with exit code 0

咱們思路如今轉換到按照列表的索引進行單個元素的輸出以後,再考慮一個問題,如何讓輸出的間隔變成1,2,3這樣,也就是輸出1,2,4,7行這樣

fileName = 'test.txt'
with open(fileName,'r',encoding='UTF-8') as f:
    lines = f.readlines()
    print(str(type(lines))+'\n'+str(lines))
linenum=1
for i in range(1,5):
    print(lines[linenum])
    linenum=linenum+i
<class 'list'>
['表頭\n', '1,數據1\n', '2,數據2\n', '3,數據3\n', '4,數據4\n', '5,數據5\n', '6,數據6\n', '7,數據7\n']
1,數據1

2,數據2

4,數據4

7,數據7


Process finished with exit code 0

emmmm........暫時就想到這麼多了,have fun :)

相關文章
相關標籤/搜索