如何计算使用Python的文本文件中的行数 [英] how to count the total number of lines in a text file using python

查看:377
本文介绍了如何计算使用Python的文本文件中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  blue 
green
yellow
黑色

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

解决方案

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

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

请注意,您不能使用 len(f),因为 f 是一个迭代器 _ 是一次性变量的特殊变量名称,请参见什么是单个下划线_的目的是你可以使用 len(f.readlines()),但是可以使用Python中的变量吗?

这将在内存中创建一个额外的列表,甚至不适用于内存不适合的大文件。


For example if my text file is:

blue
green
yellow
black

Here there are four lines and now I want to get the result as four. How can I do that?

解决方案

You can use sum() with a generator expression:

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

Note that you cannot use len(f), since f is an iterator. _ is a special variable name for throwaway variables, see What is the purpose of the single underscore "_" variable in Python?.

You can use len(f.readlines()), but this will create an additional list in memory, which won't even work on huge files that don't fit in memory.

这篇关于如何计算使用Python的文本文件中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆