Reading a textfile into a String
<p>I'm just starting to learn python and have a  textfile that looks like this:</p>

<pre><code>Hello

World


Hello
World
</code></pre>

<p>And I want to add the numbers '55' to the beggining and end of every string that starts with 'hello'</p>

<p>The numbers '66' to the beggining and every of every string that starts with 'World'</p>

<p>etc</p>

<p>So my final file should look like this:</p>

<pre><code>55Hello55

66World66


55Hello55
66World66
</code></pre>

<p>I'm reading the file in all at once, storing it in a string, and then trying to append accordingly</p>

<pre><code>fp = open("test.txt","r")
strHolder = fp.read()
print(strHolder)

if 'Hello' in strHolder:
    strHolder = '55' + strHolder + '55'
if 'World' in strHolder:
    strHolder = '66' + strHolder + '66'
print(strHolder)
fp.close()
</code></pre>

<p>However, my string values '55' and '66' are always being added to the front of the file and end of the file, not the front of a certain string and to the end of the string, where I get this output of the string:</p>

<pre><code>6655Hello

World


Hello
World
5566
</code></pre>

<p>Any help would be much appreciated.</p>

<p>You need to iterate over each line of the file in order to get the desired result. In your code you are using <code>.read()</code>, instead use <code>.readlines()</code> to get list of all lines.</p>

<p>Below is the sample code:</p>

<pre><code>lines = []
with open("test.txt", "r") as f:
     for line in f.readlines():  # &lt; Iterate over each line
         if line.startswith("Hello"):  # &lt;-- check if line starts with "Hello"
             line = "55{}55".format(line)
         elif line.startswith("World"):
             line = "66{}66".format(line)
         lines.append(line)

print "\n".join(lines)
</code></pre>

<p>Why to use <code>with</code>? Check <a href="https://docs.python.org/3/whatsnew/2.6.html#pep-343-the-with-statement" rel="nofollow">Python doc</a>:</p>

<blockquote>
  <p>The âwithâ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, Iâll discuss the statement as it will commonly be used. In the next section, Iâll examine the implementation details and show how to write objects for use with this statement.</p>
  
  <p>The âwithâ statement is a control-flow structure whose basic structure is:</p>
  
  <p>with expression [as variable]: with-block</p>
  
  <p>The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has <strong>enter</strong>() and <strong>exit</strong>() methods).</p>
</blockquote>

python