繁体   English   中英

如何使用python计算文本文件中的总行数

[英]how to count the total number of lines in a text file using python

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

blue
green
yellow
black

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

您可以将sum()与生成器表达式一起使用:

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

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

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

这个链接( 如何在Python中廉价地获得行数? )有很多潜在的解决方案,但它们都忽略了一种方法,使运行速度更快,即使用无缓冲(原始)接口,使用bytearrays,并进行自己的缓冲。

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

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 )

你可以在这里使用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'))
count=0
with open ('filename.txt','rb') as f:
    for line in f:
        count+=1

print count

一个班轮:

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

print(total_line_count)

这个也给出了文件中的no.of行。

a=open('filename.txt','r')
l=a.read()
count=l.splitlines()
print(len(count))

采用:

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

那可行。

对于那些说使用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 ()

这里是你如何通过列表理解来完成它,但这会浪费你的计算机内存的一小部分,因为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)))

我不是stackoverflow的新手,只是从来没有一个帐户,通常来这里寻求答案。 我还不能发表评论或投票。 但是我想说上面的迈克尔培根的代码非常有效。 我是Python新手,但不是编程。 我一直在阅读Python Crash Course,我想做一些事情来打破阅读封面以涵盖方法。 从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.")

如果您导入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

暂无
暂无

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

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