On Tue, May 11, 2010 at 1:00 PM, ramya natarajan <nramy...@gmail.com> wrote: > Hello, I have to read lines from > files exactly upto 1000 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
here's the pseudocode of what you're doing, it might help you understand what the problem is: for every line in the file: if the character count is less than 1000, add the length of the current line. You are missing a condition. Here is another version of your code that has the same problem, see if this helps make it clearer: lines, chars = 0,0 with open('/temp/new.txt') as f: for line in f: if chars > 1000: break chars += len(line) This sounds a lot like a homework problem so I won't give you the answer, but I hope that helps. Also do you realize you are counting newlines as well? You may not want to do this, depending on your intended application. Hope that helps, -Luke _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor