0

I am trying to get a line count of a file using command prompt. However when I execute the code I get the output of 0.

import sys
file = open(sys.argv[1],"r")
lines=0
line=file.readline()
while line !="":
  lines=lines+1
  line=file.readline()
print("Lines:"+str(lines)+"\n")
file.close()

This code works perfectly fine, the lines inside the file was deleted.And that caused the output of 0

babybirkins
  • 95
  • 1
  • 2
  • 10
  • 2
    Does this answer your question? [How to get line count of a large file cheaply in Python?](https://stackoverflow.com/questions/845058/how-to-get-line-count-of-a-large-file-cheaply-in-python) – sudonym Nov 17 '20 at 02:57
  • The code works, but [as the OP mentioned in the comments](https://stackoverflow.com/questions/64868567/how-to-get-a-line-count-of-a-file-in-python#comment114688506_64868694), the "*lines inside the data is deleted*". – Gino Mempin Nov 17 '20 at 05:27

5 Answers5

1
import sys
file = sys.argv[1]

with open(file, "r") as f:
    num_lines = len(f.readlines())
Antimon
  • 597
  • 3
  • 10
0

I think you want readlines not readline

Kenan
  • 13,156
  • 8
  • 43
  • 50
0
import sys
file = open(sys.argv[1],"r")
lines = file.readlines()
file.close()
line_count = len(lines)
print(f"There are {line_count} lines")
Epic Gamer
  • 101
  • 1
  • 10
0

to get your line count, try this:

import sys, os

def file_len(fname):
    if os.stat(file_path).st_size == 0:
        print('File is empty')
        return 0
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

print(file_len(sys.argv[1]))
sudonym
  • 3,788
  • 4
  • 36
  • 61
0

Your code runs fine for me if I run it as python myscript.py myfile.txt, using Python 3.8.5 on MacOS.

However the script could be cleaned up a little. It would be a good idea to use Python's open() context handler while reading the file, the readlines() method to get all the lines at once, and Python's built-in tools for string formatting. Then you can do the whole count very simply like this:

import sys
with open(sys.argv[1]) as file:
    lines = len(file.readlines())
print(f"Lines: {lines}\n")

You may also want to consider using Python's argparse module to handle your argument(s).

Matthias Fripp
  • 17,670
  • 5
  • 28
  • 45
  • It gives me the following error: IndexError: list index out of range – babybirkins Nov 17 '20 at 03:06
  • Yeah, I was mistaken about the order of arguments in an early version of this answer. Turns out your code runs fine for me as-is. Are you sure you're not specifying an empty file? – Matthias Fripp Nov 17 '20 at 03:07