Python-如何获取文本文件中的行数 [英] Python - How to get the number of lines in a text file

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

问题描述

我想知道是否可以不使用命令而知道多少行包含我的文件文本:

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...

推荐答案

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

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

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

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

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

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

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