Home > database >  Counting the Number of Lines in a .txt file, getting double the expected result
Counting the Number of Lines in a .txt file, getting double the expected result

Time:08-14

I'm trying to write a very basic script that will take a input file name and simply count the number of lines in the file, and print it to CMD. I am getting double the number of lines that are actually in the file when I run it though.

import sys


filename = sys.argv[-1]
with open(filename,) as f:
    LineCount = len(f.readlines())
print(LineCount)
input("Press Enter to close...")

The text file is 208 lines long, I am getting 417 back. Here is what the file looks like. It just repeats from here on out.

Asset Name              In Point            Description 
Zach And Jenv4          00:00:13:11                         
Zach And Jenv4          00:00:14:54                         
Zach And Jenv4          00:00:16:37                         
Zach And Jenv4          00:00:18:20                         
Zach And Jenv4          00:00:20:03                         
Zach And Jenv4          00:00:21:45                         
Zach And Jenv4          00:00:23:28                         
Zach And Jenv4          00:00:25:11                         
Zach And Jenv4          00:00:26:54                         
Zach And Jenv4          00:00:28:36                         
Zach And Jenv4          00:00:30:20                         
Zach And Jenv4          00:00:32:03                         
Zach And Jenv4          00:00:33:45                         
Zach And Jenv4          00:00:35:28                         
Zach And Jenv4          00:00:37:11                         
Zach And Jenv4          00:00:38:54                         
Zach And Jenv4          00:00:40:37                         
Zach And Jenv4          00:00:42:20                         
Zach And Jenv4          00:00:44:03                         
Zach And Jenv4          00:00:45:44                         
Zach And Jenv4          00:00:47:28                         
Zach And Jenv4          00:00:49:11                         
Zach And Jenv4          00:00:50:54                         

CodePudding user response:

Here's a likely explanation, but OP should look at f.readlines() content to be sure.

The file has \r\r\n line termination and the default for open is to translate \r, \n, and \r\n each to a newline when reading, so \r\r\n gets translated to \n\n. enter image description here

  • Related