Python - 如何获取文本文件中的行数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32607370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:53:33  来源:igfitidea点击:

Python - How to get the number of lines in a text file

pythonfiletextcount

提问by user3601754

I would like to know if it s possible to know how many lines contains my file text without using a command as :

我想知道是否可以在不使用以下命令的情况下知道有多少行包含我的文件文本:

with open('test.txt') as f:
    text = f.readlines()
    size = len(text)

My file is very huge so it s difficult to use this kind of approach...

我的文件非常大,所以很难使用这种方法......

回答by The6thSense

Slight modification to your approach

稍微修改您的方法

with open('test.txt') as f:
    line_count = 0
    for line in f:
        line_count += 1

print line_count

Notes:

笔记:

Here you would be going through line by line and will not load the complete file into the memory

在这里,您将逐行浏览,并且不会将完整文件加载到内存中

回答by Garogolun

The number of lines of a file is not stored in the metadata. So you actually have to run trough the whole file to figure it out. You can make it a bit more memory efficient though:

文件的行数不存储在元数据中。所以你实际上必须运行整个文件才能弄清楚。不过,您可以使其内存效率更高:

lines = 0
with open('test.txt') as f:
    for line in f:
        lines = lines + 1

回答by Kasramvd

As a Pythonic approach you can count the number of lines using a generator expression within sumfunction as following:

作为 Pythonic 方法,您可以使用sum函数内的生成器表达式计算行数,如下所示:

with open('test.txt') as f:
   count = sum(1 for _ in f)

Note that here the fileobject fis an iterator object that represents an iterator of file's lines.

请注意,这里的f文件对象是一个迭代器对象,表示文件行的迭代器。

回答by saeedgnu

with open('test.txt') as f:
    size=len([0 for _ in f])