简体   繁体   中英

Looping through a text file using islice

I want to read the lines of a text file multiple times using islice. The aim is to try, every time, to get the lines which contain an index contained in a list and, later write the file containing these lines only. I tried the following script but I realized (by printing the row numbers) that the program read the file once only despite my for loop. Why?

with open(input,'r') as inp,:
    sliced_file = islice(inp,None)

for ind in listOfInd:    
    print('ind ' + ind)
    for line_number, line in enumerate(sliced_file,start=1):
        print(line_number)
        number, rest = line.split('\t',1)

The first time the enumerate function is called on sliced_file iterator object, end of file will be reached. So next time for it to iterate through the file again, the file pointer has to be reset to the start of the file.

Also in your snippet, flow control moves out of the with block, the file will be closed and won't be available for reading.

Here is a fixed code.

inp = open(input,'r')
sliced_file = islice(inp,None)
for ind in listOfInd:    
    print('ind ' + ind)
    for line_number, line in enumerate(sliced_file,start=1):
        print(line_number)
        number, rest = line.split('\t',1)
    inp.seek(0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM