Hi all,
I am very new to programming , I am trying to do task where I have to count the number of lines that are read until the total length of the lines is 1,000 characters and also it it doesn't count characters on any line that begins with a pound sign (#).

here is my code:
char,lines = 0,0
log = open('/tmp/new.txt','r')
for count,line in enumerate(log) :
if '#' not in line :
if char + len(line) < 1000 :
char += len(line)
lines += 1

when i execute its counting all lines including '#")
its prinitng 999 and 37 instead of 45. What mistake am i doing here ? Can some one please help?

You can use the string's 'startswith' method

cnt_char = 0
log_file = open("/tmp/new.txt")

for lineno, line in enumerate(log_file): # lineno starts from 0
    if line.startswith("#"):
        continue
    cnt_char += len(line)
    if cnt_char >= 1000:
        cnt_char -= len(line)
        break

print("The first %d lines contain %d characters" % (lineno, cnt_char))

This code skips a line only if its first character is #.

The specification of the line count is ambiguous: Does a # line increase the line count but not the character count, or is it skipped entirely. Gribouillis' code ignores the line count, but you need to deal with it one way or the other.

Task has no connection to line count only total number of characters collected except # lines. Here if all characters are included in the count including (excluding exception handling, without using with) does not work if file is shorter than 1000 chars (one line fix, exercise for the student):

def thousand(fn):
    fi = open(fn,'r')
    collected,st = 0,''
    while collected<1000:
        line = fi.readline()
        if not line.startswith("#"):
            ## does not drop lines which start with spaces before #
            st += line
            collected += len(line)
        ## fix for short file here
    fi.close()
    return st[:1000]

print thousand('myfile.txt')

It is even simpler, if you do it more complicated :-)

print ''.join(
    [line for line in
        open('myfile.txt')
        if not line.startswith("#")]
        ) [:1000]

This code works also if file is shorter than 1000 chars

Edited 6 Years Ago by pyTony: short file notice

This article has been dead for over six months. Start a new discussion instead.