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

blue

green

yellow

black

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

open('data.txt')as fp:for line in fp:if line.strip():count + = 1

@alecxe会起作用吗?

是的,它会起作用,但解决方案不是pythonic,更好地使用sum()。

stackoverflow.com/questions/845058/绰绰有余;-)

如何在Python中廉价获取行数可能重复?

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

with open('data.txt') as f:

print sum(1 for _ in f)

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

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

所以pythonic,非常pythonic:O

如果你用open('data.txt')把它写成f:print sum([1 for _ in f]),它会更加迅速吗?

@jimh - 最好只使用sum(1 for _ in f)因为它隐含地使用括号内的生成器表达式而不创建1的列表。但是,您的版本sum([1 for _ in f])会在对它们求和之前创建一个1的列表,这会不必要地分配内存。

@blokeley以牺牲内存为代价更快是我的问题

@jimh这里没有这样的权衡。生成器表达式将减少,因为它不必花时间分配内存。理解可以是优化,以防您可以重用已分配的列表或字典。

这个链接(如何在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'

') 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'

') for buf in bufgen if buf )

谢谢!这个itertool实现速度非常快,让我在读取一个非常大的文件时给出一定的完成百分比。

我收到一个错误:AttributeError:'file'对象没有'raw'属性。有什么想法吗?

这里的代码是python 3特有的,原始/ unicode分裂发生在那里。我的python 2内存在这一点上并不好,但是如果你使用的是python 2,我想如果你将open()调用的模式更改为'r'并且只是将"f.raw.read()"更改为"f.read()"你将在python 2中有效地获得同样的东西。

将第一个示例中的return语句更改为return sum(map(methodcaller("count", b'

'), f_gen)),从operator导入methodcaller有助于加速任何('imap从itertools以及python2)?我也会通过1024*1024数学来节省一些额外的周期。希望看到与第二个例子的比较。

您可以在此处使用带有生成器表达式的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('

'))

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)

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

我不是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'

') 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("

Code Execution:" + str(elapsed_time) +" seconds

")

print("File contains:" + str(mycount) +" lines of text.")

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

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

使用:

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

print(num_lines)

那可行。

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

a=open('filename.txt','r')

l=a.read()

count=l.splitlines()

print(len(count))

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐