user1816377
user1816377

Reputation: 245

using len on file count (\n)

I need to write a program that count the len of the lines in file and return the number of lines >= to the len size the user asked. The problem is that len() count (\n) and I can't assume after the last line there is (\n). How can I tell len() to not count (\n) in the end of every line?

def count_long_lines(filename, size):

        f=open(filename,'r')
        count_line=0
        for line in f:
                if len(line)-1>=size:
                    count_line +=1

        print count_line
        f.close()

Upvotes: 1

Views: 1263

Answers (2)

Jon Clements
Jon Clements

Reputation: 142176

You can use (note, the .rstrip() to remove trailing newlines)

with open(filename) as f:
    print sum(1 for line in f if len(line.rstrip('\n')) >= size)

Upvotes: 6

Martijn Pieters
Martijn Pieters

Reputation: 1122322

Use .rstrip('\n') to remove any newlines from the line:

len(line.rstrip('\n'))

Upvotes: 6

Related Questions