Searching for value in a text file then printing the next line
<p>I am importing a txt file into Python 3, I am able to successfully print the item/line I am using as an identifier, however I am having difficulty printing the following line and retaining that value. </p>

<p>I am using <code>'Anchor'</code> to find the line items which follow. The number of lines between each <code>'Anchor'</code> varies, meaning sometimes there is junk/noise between <code>'Anchor'</code>, however the depth and distance from shore are always the same number of lines from Anchor. I tried to add 1 to line, as the if function lets me know that it is an <code>'Anchor'</code> value, however I get the following: </p>

<pre><code>TypeError: Can't convert 'int' object to str implicitly
</code></pre>

<p>The file looks similar to:</p>

<pre><code>asfasdfasdf
Anchor
The depth is 30 Feet
5 miles from shore

asdfasdsf
Anchor
The depth is 24 feet
8 miles from shore
Anchor
The depth is 21 feet
4 km from shore
</code></pre>

<p>Attempting with the following code:</p>

<pre><code>f = open('test.txt', 'r', encoding='utf8')

for line in f.readlines():
    if 'Anchor' in line:
        print(line+1)

f.close()
</code></pre>

<p>I would highly recommend using <a href="https://docs.python.org/2/library/stdtypes.html?highlight=iterator#iterator-types" rel="nofollow">python iterators</a>.</p>

<p>It looks like your problem would be more suited to a custom iteration, rather than using a <code>for .. in ..</code> loop:</p>

<pre><code>lines = iter(f.readlines())

while True:
    try:
        if next(lines) == 'Anchor':
            print(next(lines))
    except StopIteration:
        break
</code></pre>

<p>If you need to print additional lines after 'Anchor' just add more <code>print(next(lines))</code> calls.</p>

python file python-3.x