[Tutor] Help required to count no of lines that are until 1000 characters

ramya natarajan nramya82 at gmail.com
Tue May 11 20:00:20 CEST 2010


Hello,

I am very  beginner to programming, I  got task to Write a loop that reads
each line of a file and counts the number of lines that are read until the
total length of the lines is 1,000 characters. I have to read lines from
files exactly upto 1000 characters.

Here is my code:
 I created file under /tmp/new.txt  which has 100 lines and 2700 characters
, I wrote code will read exactly 1000 characters and count lines upto those
characters.But the problem is its reading entire line and not stopping
excatly in 1000 characters. 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
  print char , lines
  1026 , 38  ----  Its counting entire line  instead of character upto 1000
-- can some one point out what mistake am i doing here , where its not
stopping at 1000 . I am reading only char by car

My new.txt -- cotains content like
this is my new number\n

Can some one please help. I spent hours and hours to find issue but i am not
able to figure out, Any help would be greatly appreciated.
Thank you
Ramya
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100511/61ef6cc3/attachment.html>


More information about the Tutor mailing list