Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
395 views
in Technique[技术] by (71.8m points)

python - 如何在Python中便宜地获取大文件的行数?(How to get line count of a large file cheaply in Python?)

I need to get a line count of a large file (hundreds of thousands of lines) in python.

(我需要在python中获取一个大文件(数十万行)的行数。)

What is the most efficient way both memory- and time-wise?

(内存和时间最有效的方法是什么?)

At the moment I do:

(目前,我这样做:)

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

is it possible to do any better?

(有可能做得更好吗?)

  ask by SilentGhost translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

一行,可能非常快:

num_lines = sum(1 for line in open('myfile.txt'))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...