简体   繁体   中英

How to count the precise line number in a file with python?

This is the code I use to count lines in a file. I don't think it is wrong. But why the result is always one line more than I check directly using gedit ? I can just minus 1 to get the right result but I want to know why.

        file = open(filename)
        allLines = file.read()
        file.close()
        Lines=allLines.split('\n')
        lineCount = len(Lines) 

Here is the memory-efficient and pythonic way to iterate through the file and count its lines (separated with \\n).

with open(filename) as file:
    lines_count = sum(1 for line in file)

Try this :

file_handle = open('filename.txt', 'r')
newlines=len(file_handle.readlines())
print('There are %d lines in the file.' % (newlines))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM