"ramya natarajan" <nramy...@gmail.com> wrote

characters.But the problem is its reading entire line and not stopping
excatly in 1000 characters.

Do you really need to stop reading the file at 1000 characters rather than the line containing the 1000th character? That seems a very arbitrary sort of thing to do.

Can some one help what mistake i am doing here?.

  log = open('/tmp/new.txt','r')
  lines,char = 0,0
  for line in log.readlines():
       while char < 1000 :
               for ch in line :
                    char += len(ch)
               lines += 1

The problem is that the inner for loop will always process every character in the line. You want to stop (or break) from the for loop when char gets to 1000. So you need to insert a test inside the for loop. Or don't use the for loop and use an index to get the characters within your while loop.

BTW You don't want to add the length of the characters you just want to add 1...

stopping at 1000 . I am reading only char by car

No you are not, you are reading all the chars in every line that you read from the file. In fact even if you fix this loop error you will still be reading the full line from the file. Thats why I asked if you really had to stop reading the file at 1000 chars, because if so this design is fundamentally wrong.

But I suspect you only need to stop reading at the line containing the 1000th char... If that is so there is an easier way to do it:

# pseudo code
chars = 0
for count, line in enumerate(file)
    if chars + len(line) < 1000
       chars += len(line)
    else: break
print "1000 chars read in", count, "lines"

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to