Stefan
Stefan

Reputation: 2518

position of string in a file

I want to find the position of a certain string in a file to know, where I should start editing.

At the moment, I'm using the re module to convert a file in a list of bools and get the position with the index function.

Question: Is there a better/shorter way to achieve this goal?


In this example, I want to find the first line, where the letter "b" appears.

Example file:

a
b
c
b

Code:

#!/usr/bin/python

import re

infile = open("examplefile","r")
indata = infile.readlines()
infile.close()

finder = re.compile("b")
matches = [True if finder.search(s) else False for s in indata]
print(matches.index(True))

Output:

1

Upvotes: 1

Views: 139

Answers (2)

peixe
peixe

Reputation: 1292

Just for the sake of completeness, if it does not have to be perform in python, you may use bash's grep.

    grep -nr 'string_to_search' your_file

It will return the number of line right before your match.

Upvotes: 0

thefourtheye
thefourtheye

Reputation: 239463

We can use a generator expression, like this

with open("Input.txt") as in_file:
    print(next(idx for idx, line in enumerate(in_file) if "b" in line))
# 1

Note: This raises StopIteration if the string being searched is not found in the file.

Upvotes: 2

Related Questions