python - 我如何打印/返回文件中的行数

标签 python file count readline lines

<分区>

Possible Duplicate:
How to get line count cheaply in Python?

我想打印一个文件中有多少行。

到目前为止我所拥有的是这个,但它会打印每一行的编号,我不确定如何让 Python 只打印最后一行。

filename = input('Filename: ')

f= open(filename,'r') 

counter = 1 

line = f.readline() 
while(line): 
    clean_line = line.strip() 
    print(counter) 
    line = f.readline()
    counter += 1
f.close()

最佳答案

我会去……

with open('yourfile') as fin:
    print sum(1 for line in fin)

这节省了将文件读入内存以获取其长度。

关于python - 我如何打印/返回文件中的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13306789/

相关文章:

python - SIFT输入到ANN

python - 使matplotlib python中的hexbin填充方轴上的空白区域?

mysql - 您是否应该始终在 SELECT * 之前执行 COUNT(*) 以确定是否有任何行?

c++ - 从 .txt 文件中读取字母和数字

python - 查找列表中两个整数之间的最大增量

windows - 如何从文件名中的字符中删除西类牙口音?

java - 如何安装 assets 文件夹大小 > 1GB 而 apk 最大大小 = 50 MB 的 android 应用程序?

Python 编程 - 输入/输出

mysql - 使用 MySQL 中同一个表的 COUNT 连接两个查询

python - 通过跨多索引级别分布来乘以系列