Text file line count - different number in python2 vs python3

44 Views Asked by At

I am reading a text file using this command:

print(len(list(open(filename))))

Now, when I run it in Python2 I get 5622862 lines, but when I read it with Python3 I get 5622865 lines. How can it be? Btw, when I do in command line cat file.txt | wc -l I get same result as Python2.

This is driving me nuts. Two files that should have same line length (5622862) indeed have the same length in python2, but not in python3 (5622862 vs 5622865). Can it be that python3 has a bug?

Doing a different read in python3 does not work either:

list(open(filename, "r", encoding="utf-8"))
1

There are 1 best solutions below

0
Nathan B On

Doing

print(len(list(open(filename, "r", encoding="utf-8", newline="\n"))))

is backward compatible to Python 2