【问题标题】:How do i print/return the number of lines in a file [duplicate]我如何打印/返回文件中的行数[重复]
【发布时间】:2012-10-29 16:43:52
【问题描述】:

可能重复:
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()

【问题讨论】:

    标签: python file count readline lines


    【解决方案1】:

    我会去……

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

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

    【讨论】:

    • 这里的最佳解决方案。我非常懒惰。
    【解决方案2】:

    如果您不需要在每一行上循环,您可以使用:

    counter = len(f.readlines())
    

    【讨论】:

    • 谢谢!不知道我可以在这里使用 len 功能!
    【解决方案3】:
    f = open(filename, 'r')
    lines = f.readlines()
    number_of_lines = len(lines)
    f.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-04
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      相关资源
      最近更新 更多