Reputation: 99
I want to know the number of row of a text file. How can I do this?
Upvotes: 1
Views: 1575
Reputation: 74675
if iterating over a file:
for line_no, line in enumerate(f, start=1):
or if counting the lines in a file (f
):
count = sum( 1 for line in f )
Upvotes: 4
Reputation: 18590
As @Dan D. said, you can use enumerate() on the open file. The default is to start counting with 0, so if you want to start the line count at 1 (or something else), use the start
argument when calling enumerate(). Also, it's considered poor practice to use "file" as a variable name, as there is a function by that name. Thus, try something like:
for line_no, line in enumerate(open(file_name), start=1):
print line_no, line
Upvotes: 1
Reputation: 39014
f = open("file.text")
count = sum(1 for line in f)
which is equivalent to
count = 0
for line in f:
count+=1
Upvotes: 2
Reputation: 839
f = open('textfile.txt', 'rb')
len(f.readlines())
readlines() method returns a list where each index holds a line of textfile.txt.
Upvotes: 3