3

Possible Duplicate:
How to get line count cheaply in Python?

In my work i need to open a file and count no. of lines in that, i tried with this

Last_Line = len(open(File_Name).readlines())

It was working fine. Now i have a problem, actual no. of lines in the file is 453, but if i print Last_Line it is showing only 339. If i try

print linecache.getline(File_Name, 350)

it is displaying the contents of line no. 350.

I tried opening the file in all modes. Whether its problem with file or with my logic? Please help.

thank you

Community
  • 1
  • 1
user19911303
  • 449
  • 2
  • 9
  • 34

1 Answers1

5

You have mixed line endings. Your IDE is treating them all as valid, while Python is not. Open the file with the universal newlines flag "U" to have Python take them all as valid line endings.

>>> f = open("file.txt", "w")
>>> f.write("a\rb\nc\r\nd\n\re\n")
>>> f.close()
>>> open("file.txt").readlines()
['a\rb\n', 'c\r\n', 'd\n', '\re\n']
>>> open("file.txt", 'rU').readlines()
['a\n', 'b\n', 'c\n', '\n', 'd\n', '\n', 'e\n']

The documentation for linecache does not appear to specify how it handles line endings. Empirically, it uses universal newlines:

>>> for n in range(1, 8):
...   linecache.getline('file.txt', n)
...
'a\n'
'b\n'
'c\n'
'\n'
'd\n'
'\n'
'e\n'
Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88