如何在文本文件中找到某个字符串的行号?

时间:2019-07-17 05:36:54

标签: python python-3.x

编辑:感谢所有帮助人员!我已经在评论部分找到了答案,但是我不知道如何将评论标记为已回答!谢谢Dainius Preimantas回答了我的问题!

我有一个文本文件,想在文本文件中找到某个字符串,然后返回该字符串所在行的编号? 例如:

with open("File.txt", "r+") as f:
    f.find(stringvalue)
    linenumber = #whatever line number value is returned

文本文件(“ File.txt”):

  

PasswordBank,jack789

     

BankEpic,Epic1234

     

Bank1,Bank123

     

Master,Master123

3 个答案:

答案 0 :(得分:0)

尝试这样的事情:

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

以后,在提出问题时,请参阅我们关于how do i ask a good question?的指南

答案 1 :(得分:0)

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")

答案 2 :(得分:0)

此方法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