text - Python - Nested loop that doesn't work when reading a file -
this nested loop works fine when reading lists:
list = [1,2,3,4,5] num = 0 while num < 5: in list: print(i) num += 1
this loop print elements in list. problem doesn't work @ when reading textfiles. instead of printing first 5 lines of text read through , print them.
f = open(r'c:\users\me\python\bible.txt') num = 0 while num < 50: line in f: print(line) num += 1
i can assume num variable doesn't increment after each iteration, there reason this, , there solution?
the code
for line in f: print line num += 1
is looping on lines in file. @ same time increment num
one. @ end of for-loop num
equal number of lines in files, larger 50, exit while-loop.
using style should write:
for line in f: print line num += 1 if num > 50: break
also first code has same problem. why need 2 loops if want loop on 1 construction in 1 dimension? codes not pythonic, illustration should rewrite them as:
list = [1,2,3,4,5] in list: print i,line in enumerate(f): print line if > 50: break
python text iteration
No comments:
Post a Comment