如何使用python查找文本文件中的行数?

时间:2014-05-28 06:52:12

标签: python

  1. 我需要获取给定.tst文件的文本文件...并找到其中的行数
  2. 我的输出为0 ..
  3. 我需要执行两次程序以获取这些文本文件
  4. 我的代码有问题吗?
  5. name_of_file = raw_input("tst file address please:")
    
    import re
    f = open(name_of_file+".tst",'r')
    data = f.read()
    y = re.findall(r'Test Case:(.*?)TEST.UNIT:',data,re.DOTALL)
    fb = open('tcases.txt' ,'w' )
    for line in y :
     fb.write(line)
    z = re.findall(r'TEST.SUBPROGRAM:(.*?)TEST.NEW',data,re.DOTALL)
    fc = open('tsubprgs.txt' ,'w' )
    for line in z :
     fc.write(line)
    x = re.findall(r'TEST.UNIT:(.*?)TEST.SUBPROGRAM:',data,re.DOTALL)
    fa = open('tunits.txt' ,'w' )
    for line in x :
     fa.write(line)
    
    with open('tunits.txt') as foo:
     lines = len(foo.readlines())
     print lines
    

3 个答案:

答案 0 :(得分:8)

试试这个

with open(<pathtofile>) as f:
      print len(f.readlines())

答案 1 :(得分:1)

在您的示例中,re.findall()返回一个列表,您可以在不重新打开和计算结果文件的情况下获取匹配数,例如:

x = re.findall(r'TEST.UNIT:(.*?)TEST.SUBPROGRAM:',data,re.DOTALL)
num_tunits = len(x)

请参阅other answers了解文件行计数的想法。

答案 2 :(得分:0)

myfile = "names.txt"

num_names = 0

with open(myfile, 'r') as f:
    for line in f:
    names = line.split()

    num_names += len(names)

print (num_names)