繁体   English   中英

读取文件行数的更快方法

[英]Faster way of reading number of lines in file

我正在尝试打开一个文件,并计算文件中的行数。

我为此使用的代码是:

def line_Count(x):
    with open(x,'r') as iFile:  # Open passed in file
        lines = iFile.readlines() # Read each line in the file
        line_Count = len(lines) # Count the number of lines
        return line_Count       # Return the line count

这适用于少量数据(0.073 秒内 10k 行)。

但是,对于大文件(1m 行),需要 15 分钟以上才能完成。

有没有更快完成任务的方法?

前面的示例来自 5 年多前,其中一些解决方案已被弃用。

使用 xreadlines(因为您正在处理大文件)可能会在 Python2 中为您带来提升:

count = 0
for line in open(file_path).xreadlines(): count += 1

或者,由于您使用的是 Python 3 ,因此使用生成器的 memory 密集度可能较低:

count = sum(1 for i in open(file_path, 'rb'))

或者

def blocks(files, size=65536):
    while True:
        b = files.read(size)
        if not b: break
        yield b

with open(file_path, "r",encoding="utf-8",errors='ignore') as f:
    print (sum(bl.count("\n") for bl in blocks(f)))

最后你可以“作弊”并使用子进程:

int(subprocess.check_output("wc -l " + file_path).split()[0])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM