How to find number of lines in text file using python?
本问题已经有最佳答案,请猛点这里访问。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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 |
试试这个
1 2 | with open(<pathtofile>) as f: print len(f.readlines()) |
在您的示例中,
1 2 | x = re.findall(r'TEST.UNIT:(.*?)TEST.SUBPROGRAM:',data,re.DOTALL) num_tunits = len(x) |
有关文件行计数的想法,请参阅其他答案。
1 2 3 4 5 6 7 8 9 10 11 | 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) |