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
CodePudding user response:
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]
CodePudding user response:
If I am understanding correctly, something like this might be what you are looking for.
def FindLineIndexOfFile(file, text):
file = open(file, "r")
line_count = 0
for lines in file.readlines():
line_count = 1
line_index = lines.strip()
if line_index == text:
file.close()
return line_count
index = FindLineIndexOfFile("sample.txt", "hello world")
print(index)
