27

例如,如果我的文本文件是:

blue
green
yellow
black

这里有四行,现在我想得到四行的结果。我怎样才能做到这一点?

4

11 回答 11

53

您可以使用sum()生成器表达式:

with open('data.txt') as f:
    print sum(1 for _ in f)

请注意,您不能使用len(f),因为f它是一个迭代器_是一次性变量的特殊变量名,请参阅Python 中单个下划线“_”变量的用途是什么?.

您可以使用len(f.readlines()),但这会在内存中创建一个额外的列表,它甚至不适用于不适合内存的大文件。

于 2013-09-25T09:45:52.823 回答
21

此链接(如何在 Python 中廉价地获取行数?)有很多潜在的解决方案,但它们都忽略了一种使该程序运行得更快的方法,即使用无缓冲(原始)接口、使用字节数组和进行自己的缓冲.

使用计时工具的修改版本,我相信以下代码比提供的任何解决方案都更快(并且稍微更像 Python):

def _make_gen(reader):
    b = reader(1024 * 1024)
    while b:
        yield b
        b = reader(1024*1024)

def rawpycount(filename):
    f = open(filename, 'rb')
    f_gen = _make_gen(f.raw.read)
    return sum( buf.count(b'\n') for buf in f_gen )

以下是我的时间安排:

rawpycount        0.0048  0.0046   1.00
bufcount          0.0074  0.0066   1.43
wccount             0.01    0.01   2.17
itercount          0.014   0.014   3.04
opcount            0.021    0.02   4.43
kylecount          0.023   0.021   4.58
simplecount        0.022   0.022   4.81
mapcount           0.038   0.032   6.82

我会把它贴在那里,但我是一个相对较新的堆栈交换用户,没有必要的甘露。

编辑:

这可以通过使用 itertools 内联的生成器表达式完全完成,但看起来很奇怪:

from itertools import (takewhile,repeat)

def rawbigcount(filename):
    f = open(filename, 'rb')
    bufgen = takewhile(lambda x: x, (f.raw.read(1024*1024) for _ in repeat(None)))
    return sum( buf.count(b'\n') for buf in bufgen if buf )
于 2014-12-17T03:05:34.073 回答
8

您可以sum()在此处使用生成器表达式。生成器表达式将[1, 1, ...]达到文件的长度。然后我们调用sum()将它们加在一起,得到总数。

with open('text.txt') as myfile:
    count = sum(1 for line in myfile)

根据您的尝试,您似乎不想包含空行。然后你可以这样做:

with open('text.txt') as myfile:
    count = sum(1 for line in myfile if line.rstrip('\n'))
于 2013-09-25T09:45:58.623 回答
5
count=0
with open ('filename.txt','rb') as f:
    for line in f:
        count+=1

print count
于 2013-09-25T09:45:03.807 回答
2

一个班轮:

total_line_count = sum(1 for line in open("filename.txt"))

print(total_line_count)
于 2017-01-31T17:56:05.543 回答
0

这也给出了文件中的行数。

a=open('filename.txt','r')
l=a.read()
count=l.splitlines()
print(len(count))
于 2016-09-29T10:58:15.113 回答
0

利用:

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

那可行。

于 2017-02-24T20:46:14.433 回答
0

对于说使用 with open ("filename.txt","r") as f 你可以做的人anyname = open("filename.txt","r")

def main():

    file = open("infile.txt",'r')
    count = 0
    for line in file:
            count+=1

    print (count)

main ()
于 2017-05-10T21:18:02.213 回答
0

这是您可以通过列表理解来做到这一点的方法,但这会浪费您的计算机内存,因为 line.strip() 已被调用两次。

     with open('textfile.txt') as file:
lines =[
            line.strip()
            for line in file
             if line.strip() != '']
print("number of lines =  {}".format(len(lines)))
于 2018-01-15T14:11:09.283 回答
0

我对stackoverflow并不陌生,只是从来没有帐户,通常来这里寻求答案。我还不能评论或投票给答案。但是想说的是上面 Michael Bacon 的代码运行良好。我是 Python 新手,但不是编程新手。我一直在阅读 Python 速成课程,我想做一些事情来打破从头到尾的阅读方法。从 ETL 甚至数据质量角度使用的一种实用程序是独立于任何 ETL 捕获文件的行数。该文件有 X 行,您导入 SQL 或 Hadoop,最终得到 X 行。您可以在最低级别验证原始数据文件的行数。

我一直在玩他的代码并进行一些测试,到目前为止,这段代码非常有效。我创建了几个不同的 CSV 文件、各种大小和行数。您可以在下面查看我的代码,我的评论提供了时间和详细信息。上面提供的代码 Michael Bacon 的运行速度比仅循环行的普通 Python 方法快 6 倍。

希望这可以帮助某人。


 import time
from itertools import (takewhile,repeat)

def readfilesimple(myfile):

    # watch me whip
    linecounter = 0
    with open(myfile,'r') as file_object:
        # watch me nae nae
         for lines in file_object:
            linecounter += 1

    return linecounter

def readfileadvanced(myfile):

    # watch me whip
    f = open(myfile, 'rb')
    # watch me nae nae
    bufgen = takewhile(lambda x: x, (f.raw.read(1024 * 1024) for _ in repeat(None)))
    return sum(buf.count(b'\n') for buf in bufgen if buf)
    #return linecounter


# ************************************
# Main
# ************************************

#start the clock

start_time = time.time()

# 6.7 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfilesimple("c:/junk/book1.csv")

# 0.67 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfileadvanced("c:/junk/book1.csv")

# 25.9 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")

# 5.7 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")


# 292.92 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")

# 57 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")


#stop the clock
elapsed_time = time.time() - start_time


print("\nCode Execution: " + str(elapsed_time) + " seconds\n")
print("File contains: " + str(mycount) + " lines of text.")
于 2018-12-04T23:09:45.707 回答
0

如果您导入pandas,那么您可以使用该shape功能来确定这一点。不确定它的表现如何。代码如下:

import pandas as pd
data=pd.read_csv("yourfile") #reads in your file
num_records=[]               #creates an array 
num_records=data.shape       #assigns the 2 item result from shape to the array
n_records=num_records[0]     #assigns number of lines to n_records
于 2019-02-20T23:12:21.717 回答