Python: reading text, readlines() vs iter() -


i have text file, blocks of text, each separated line break. there m blocks, each n lines of text. want read n lines each of m blocks, n<=n , m<=m.

i have tried similar following:

num_blocks = 4 # or whatever value choose num_lines = 3 # or whatever value choose  open('file.txt', 'r') f:     lines = f.readlines()     block_num = 0     line_num = 0     line in lines:         # line .....         line_num += 1         # has specified number of lines been read?         if line_num == num_lines:             block_num += 1             # has specified number of blocks been read?             if block_num == num_blocks:                 break;             else:                 line_num = 0 

however, when n<n, need skip on remaining lines in current block. have tried putting

if line != '\n':     continue 

next # line ....., skips entire first block.

alternatively, have tried creating iterator it = lines.iter() , incrementing each 1 accordingly. problem approach there no way of knowing when end of file has been reached. readlines() me, don't know how know when last line has been reached if using interator.

any help? thanks!

you can test end of iterator so:

try:     it.next() except stopiteration:     *do something* 

the stopiteration exception iterator throws when there nothing left iterate.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -