This is the code i have at the moment
print "Please input the filename:"
n = raw_input()
f = open(n,"r")
x = 0
for line in f.readlines():
print line
x+=1
if x % 20 == 0:
break
q = raw_input()
if q == "":
x+= 20
continue
Things the program should do:
1) Ask for a filename
2) Read the file
3) Print the first 20 lines of the file
4) Stop working after the first 20 lines and wait for an Enter keypress
5) If Enter is pressed show the next 20 lines of the file (20->40 and so on)
Current problem: The loop doesn’t restart, it only shows the first 20 lines and then stops working.
This reads the whole file into memory so you might not want to use slices if it’s a huge file. But if it’s a huge file, you’re unlikely to want to step through it twenty lines at a time 😉
The major change is that we are opening the file using a
withstatement. This is much nicer than usingopen/closeand guarantees that the file will always be closed.in the code that you posted, when you executed
break, you were exiting your look.breakleaves the loop so you only want to use it for that purpose.just calling a blocking operation likeraw_input` suffices if you just need to pause execution for some reason (like waiting on the user).also, the
continueis entirely unnecessary. At the end of the body of a loop, it has no choice but tocontinueWhat were you thinking with the lines
if q == "": x += 20? first off, it should just beif not q: x += 20(empty string (like empty lists/dicts/tuples) evaluates toFalse) and second, this would skip the next 20 lines. Is this a requirement that you haven’t shared?