word = "some string"
file1 = open("songs.txt", "r")
flag = 0
index = 0
for line in file1:
index = 1
if word in line:
flag = 1
break
if flag == 0:
print(word " not found")
else:
#I would like to print not only the line that has the string, but also the previous and next lines
print(?)
print(line)
print(?)
file1.close()
CodePudding user response:
Use contents = file1.readlines()
which converts the file into a list.
Then, loop through contents
and if word
is found, you can print contents[i]
, contents[i-1]
, contents[i 1]
. Make sure to add some error handling if word
is in the first line as contents[i-1]
would throw and error.
CodePudding user response:
word = "some string"
file1 = open("songs.txt", "r")
flag = 0
index = 0
previousline = ''
nextline = ''
for line in file1:
index = 1
if word in line:
finalindex = index
finalline = line
flag = 1
elsif flag==1
print(previousline finalline line)
print(index-1 index index 1)
else
previousline = line
You basically already had the main ingredients:
- you have line (the line you currently evaluate)
- you have the index (index)
the todo thus becomes storing the previous and next line in some variable and then printing the results.
have not tested it but code should be something like the above.....
splitting if you find the word, if you have found it and you flagged it previous time and if you have not flagged it.
i believe the else-if shouldnt fire unless flag ==1