By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,965 Members | 1,450 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,965 IT Pros & Developers. It's quick & easy.

Loop of a text file showing first 20 lines?

P: n/a
How can I code a loop of a text file showing it's first 20 lines and after pressing enter it shows the next 20 lines and so on?
Sep 30 '10 #1
Share this Question
Share on Google+
5 Replies

Expert 100+
P: 983

Try putting something together and posting it, if you're having troubles with the code. We'll gladly help.

To get off square one with python, go try one of the tutorials that are all over the 'Net. It'll get you a lot farther than asking for code chunks.

Sep 30 '10 #2

P: n/a
OK, I've got it to show the file's first line 20 times over and over again.
Expand|Select|Wrap|Line Numbers
  1. f = open("story.txt", "r")
  2. a = f.readlines()
  3. while True:
  4.     print 20*a
Sep 30 '10 #3

P: n/a
I've got it to show the first 20 lines of a text file over and over.
[code] story = open("11.txt", "r")
a = story.readline()
b = story.readline()
c = story.readline()
d = story.readline()
e = story.readline()
f = story.readline()
g = story.readline()
h = story.readline()
i = story.readline()
j = story.readline()
k = story.readline()
l = story.readline()
m = story.readline()
n = story.readline()
o = story.readline()
p = story.readline()
q = story.readline()
r = story.readline()
s = story.readline()
t = story.readline()
all = a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t
while True:
print all
There's gotta be a beter way to do this :D
Sep 30 '10 #4

Expert 100+
P: 983
Use an inner loop which does story.readline() once, and prints each individual line independently.

Then your outer loop can wait patiently for the next user input, then it releases the inner loop, etc....
Sep 30 '10 #5

Expert Mod 2.5K+
P: 2,851
Here's some pseudocode:

Open the file, assign to an identifier

Start a while loop, maybe while True:

Initialize an empty list

I am using file method next() which raises a StopIteration exception when reaching the end of a file, so start a try/except block

Start a for loop over a range of 20

Append the next line of the file to the list using file method next(), end of for loop

Print the list using string method join
Expand|Select|Wrap|Line Numbers
  1. '\n'.join(thelist)
Call raw_input() which pauses processing

Now for the except part of the try/except block (except StopIteration:)

If there is anything in the list, print it

Break from the loop
Oct 1 '10 #6

Post your reply

Sign in to post your reply or Sign up for a free account.