For a given text file (sample.txt), I would like to get index value based on a string that is present on that line (index).
An example file contains following text (sample.txt):
line 1: open a file.
line 2: Read a file and store it in a variable.
line 3: check condition using ‘in’ operator for string present in the file or not.
line 4: If the condition true print the index in which the string is found.
line 5: Close a file.
if my target string is ‘variable’. The output I would like to have is:
2
>Solution :
This should do:
def indicesOfQueryOnFile(query, file):
with open(file, 'r') as f:
cleanLines = [line for line in f.readlines() if len(line.strip()) > 0]
indices = [i + 1 for i, line in enumerate(cleanLines) if query in line]
return indices
For the text file:
line 1: open a file.
line 2: Read a file and store it in a variable.
line 3: check condition using ‘in’ operator for string present in the file or not.
line 4: If the condition true print the index in which the string is found.
line 5: Close a file.
another line with variable
It would output:
indicesOfQueryOnFile('variable', 'test.txt')
# [2, 6]