3
  1. i need to get a text file fro given .tst file... and find number of lines in it
  2. I'm getting 0 as output..
  3. I Need to execute program twice for getting those text files
  4. Is there a problem with my code??
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
Yaswanth
  • 113
  • 1
  • 1
  • 7
  • Have you checked if `x = re.findall(r'TEST.UNIT:(.*?)TEST.SUBPROGRAM:',data,re.DOTALL)` matches anything at all? Have you checked manually if the file `tunits.txt` is empty? – Stefan van den Akker May 28 '14 at 06:59
  • yes.. i checked it .. and found it empty... ohh btw the problem is solved...i just added this fa.close() ... and every thing looks fine.. thanks anyway – Yaswanth May 28 '14 at 07:49
  • @user3682409 Then you should add an answer yourself. – Bakuriu May 28 '14 at 09:24

3 Answers3

9

try this

with open(<pathtofile>) as f:
      print len(f.readlines())
loki
  • 387
  • 2
  • 8
1

In your example, re.findall() returns a list for which you can obtain the number of matches without reopening and counting the result file, e.g.:

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

See other answers for file line counting ideas.

Community
  • 1
  • 1
mhawke
  • 84,695
  • 9
  • 117
  • 138
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)
  • 1
    You can make this answer more useful by adding text explaining what this code does and how it solves the problem. Answers that teach are much more useful than code without explanation. – Ryan Bemrose Jul 05 '16 at 22:27