开发者

Python: How to know the number of row of a text file

开发者 https://www.devze.com 2023-03-18 01:33 出处:网络
I want to know the number of row of a text file. How can开发者_高级运维 I do this?if iterating over a file:

I want to know the number of row of a text file. How can开发者_高级运维 I do this?


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 )


f = open('textfile.txt', 'rb')
len(f.readlines())

readlines() method returns a list where each index holds a line of textfile.txt.


f = open("file.text")
count = sum(1 for line in f)

which is equivalent to

count = 0
for line in f:
   count+=1


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
0

精彩评论

暂无评论...
验证码 换一张
取 消