如何使用python查找文本文件中的行数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23904627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:38:32 来源:igfitidea点击:
How to find number of lines in text file using python?
提问by Yaswanth
- i need to get a text file fro given .tst file... and find number of lines in it
- I'm getting 0 as output..
- I Need to execute program twice for getting those text files
- Is there a problem with my code??
- 我需要从给定的 .tst 文件中获取一个文本文件......并找到其中的行数
- 我得到 0 作为输出..
- 我需要执行两次程序才能获取这些文本文件
- 我的代码有问题吗??
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
采纳答案by loki
try this
尝试这个
with open(<pathtofile>) as f:
print len(f.readlines())
回答by mhawke
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.:
在您的示例中,re.findall()
返回一个列表,您可以在不重新打开和计算结果文件的情况下获取匹配数,例如:
x = re.findall(r'TEST.UNIT:(.*?)TEST.SUBPROGRAM:',data,re.DOTALL)
num_tunits = len(x)
See other answersfor file line counting ideas.
有关文件行计数的想法,请参阅其他答案。
回答by mrjonasmeyer
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)