如何以最有效的内存和时间方式获取大文件的行数?
def file_len(filename):
with open(filename) as f:
for i, _ in enumerate(f):
pass
return i + 1
如何以最有效的内存和时间方式获取大文件的行数?
def file_len(filename):
with open(filename) as f:
for i, _ in enumerate(f):
pass
return i + 1
当前回答
print open('file.txt', 'r').read().count("\n") + 1
其他回答
这段代码更短、更清晰。这可能是最好的方法:
num_lines = open('yourfile.ext').read().count('\n')
如果文件能放进内存,那么
with open(fname) as f:
count = len(f.read().split(b'\n')) - 1
我使用的最简单和最短的方法是:
f = open("my_file.txt", "r")
len(f.readlines())
我发现你可以。
f = open("data.txt")
linecout = len(f.readlines())
会给你答案吗
为什么下面的方法行不通呢?
import sys
# input comes from STDIN
file = sys.stdin
data = file.readlines()
# get total number of lines in file
lines = len(data)
print lines
在这种情况下,len函数使用输入行作为确定长度的方法。