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 are reading the whole file at once with <code>.read()</code>.</p>

<p>You can read it line by line in a <code>for</code> loop.</p>

<pre><code>new_file = []
fp = open("test.txt", "r")
for line in fp:
    line = line.rstrip("\n")  # The string ends in a newline
                              # str.rstrip("\n") removes newlines at the end
    if "Hello" in line:
        line = "55" + line + "55"
    if "World" in line:
        line = "66" + line + "66"
    new_file.append(line)
fp.close()
new_file = "\n".join(new_file)
print(new_file)
</code></pre>

<p>You could do it all at once, by reading the whole file and splitting by "\n" (newline)</p>

<pre><code>new_file = []
fp = open("text.txt")
fp_read = fp.read()
fp.close()
for line in fp_read.split("\n"):
    if "Hello" # ...
</code></pre>

<p>but this would load the whole file into memory at once, while the for loop only loads line by line (So this may not work for larger files).</p>

<p>The behaviour of this is that if the line has "Hello" in it, it will get "55" before and after it (even if the line is "   sieohfoiHellosdf  ") and the same for "World", and if it has both "Hello" and "World" (e.g. "Hello, World!" or "asdifhoasdfhHellosdjfhsodWorldosadh") it will get "6655" before and after it.</p>

<p>Just as a side note: You should use <code>with</code> to open a file as it makes sure that the file is closed later.</p>

<pre><code>new_file = []
with open("test.txt") as fp:  # "r" mode is default
    for line in fp:
        line = line.rstrip("\n")
        if "Hello" in line:
            line = "55" + line + "55"
        if "World" in line:
            line = "66" + line + "66"
        new_file.append(line)
new_file = "\n".join(new_file)
print(new_file)
</code></pre>

python