![](/img/trans.png)
[英]How can I find the row number of a certain string in a text file in Python?
[英]How do I find the line number of a certain string in a text file?
编辑:感谢所有帮助家伙! 我已经在评论部分找到了我的答案,但我不知道如何将评论标记为已回答! 谢谢你,Dainius Preimantas 回答我的问题!
我有一个文本文件,想在文本文件中找到某个字符串,然后返回该字符串所在的行号? 例如:
with open("File.txt", "r+") as f:
f.find(stringvalue)
linenumber = #whatever line number value is returned
文本文件(“File.txt”):
密码银行,jack789
BankEpic,Epic1234
Bank1,Bank123
大师,大师123
尝试这样的事情:
f=open('filename.txt','r')
text=f.read().split('\n')
string_to_find='string'
for line in range(text):
if string_to_find in text[line]:
return line
将来,在提问时,请参阅我们的指南,了解如何提出好问题?
substring = "42 is the answer"
filename = "file.txt"
with open(filename, "r") as file:
line = file.readline()
i = 1
flag = False
while line:
if substring in line: #Or any other string matching condition
flag = True
if flag:
break
line = file.readline()
i += 1
if flag:
print(i)
else:
print("Line not found")
这 100% 有效 我为你试过了
placeholder = 0
file = open("filename.txt", "r")
all_lines = file.readlines()
while placeholder < len(all_lines):
each_line = all_lines[placeholder]
if " yourString " in each_line:
print("yes in line: " + str(placeholder+1))
placeholder += 1
else:
placeholder += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.