如何使用python计算文本文件中的总行数 [英] how to count the total number of lines in a text file using python
本文介绍了如何使用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?
推荐答案
您可以使用 sum()
带有生成器表达式:
You can use sum()
with a generator expression:
with open('data.txt') as f:
print sum(1 for _ in f)
请注意,您不能使用 len(f)
,因为 f
是一个 迭代器._
是一次性变量的特殊变量名,参见单下划线的用途是什么_"Python 中的变量?.
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?.
您可以使用 len(f.readlines())
,但这会在内存中创建一个额外的列表,它甚至不适用于不适合内存的大文件.
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屋!
查看全文