On 12-May-2010, at 12:32 AM, spir ☣ wrote:

> On Tue, 11 May 2010 11:00:20 -0700
> ramya natarajan <nramy...@gmail.com> wrote:
> 
>> 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
> 
> Either you read line per line, but then you cannot stop exactly at the 1000th 
> character; or you traverse the text char per char, but this is a bit picky.
> I would read line per line, and when count >= 1000, read chars inside current 
> line to get to the 1000th, if needed.
> (Your specification does not state this, but your disappointment seems to be 
> about that issue ;-)
> 
> Denis

You can try read instead of readlines.
Something like...
print 'Number of lines till 1000th character:', 
len(open('/tmp/new.txt','r').read(1000).split('\n'))

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

Reply via email to