-1

So I have a (text) file with like a dozen or so lines of text, and my assignment is to count the lines using a function. I have seen other solutions for such a task, but they used the enumerate function.

My class has not learned that yet, so I'm trying to figure out how to do it without enumerate.

I was thinking I would write the function to count the \n in the text file

Would that work? How would I go about doing that? Could I just run a split and count the splits somehow?

Here is my code so far, it isn't very far:

def num_lines_in_file():

    path = 'planets.txt'
    file_handle - open(path)
    count = 0

    for line in file_handle:
        count += #here is where i'm lost

print(f"\nProblem 2: {num_lines_in_file()}")
norok2
  • 25,683
  • 4
  • 73
  • 99
gnenadov
  • 25
  • 6

4 Answers4

2

You've read one line, so increase the count by one:

for line in file_handle:
    count += 1

P.S. Also note that your function is lacking a return statement.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

x += y is a proxy for x = x + y.

for i, x in enumerate(sequence):
    ...

is roughly equivalent to:

i = 0
for x in sequence:
    ...
    i += 1

You have enough info to fix your code now.

norok2
  • 25,683
  • 4
  • 73
  • 99
0

How about

def num_lines_in_file():
    path = 'planets.txt'
    file_handle = open(path, "r")
    return len(file_handle.readlines())

Please check the docs

Cem Güler
  • 625
  • 12
  • 22
  • 2
    unecessarily inefficient... – juanpa.arrivillaga Oct 03 '19 at 20:10
  • 2
    This unnecessarily loads the content of the entire file into memory before it can count. – blhsing Oct 03 '19 at 20:11
  • @blhsing even worse, it loads it into a `list` of lines. – juanpa.arrivillaga Oct 03 '19 at 20:11
  • thanks, this got me the result I was looking for, and it is exactly the kind of syntax we've been using in my class. Can you explain to me though, how this function is operating? Does "return len(file_handle.realines())" count the linebreaks? Is that what is leading to the result? Sorry, we are only 3 weeks in and I am very new. – gnenadov Oct 03 '19 at 20:18
  • @gnenadov readlines method parses the file and splits the lines using the end of file (EOF) character into a python list. This actually solves your problem but the other commenters are actually right on one point that readlines() actually reads the whole file before creating the array and the array is actually useless because only len() method is used to find the actual line count. Also the code I provided does not close the file so that is another a minus point :) – Cem Güler Oct 03 '19 at 20:25
0

You could use a list comprehension and simply sum it up:

sum([1 for line in open('/tmp/f.py')])
# or as a generator, as mentioned by Daniel Mesejo:
sum([1 for line in open('/tmp/f.py')])

Output:

26
Maurice Meyer
  • 17,279
  • 4
  • 30
  • 47