'Python Append Not Working

So most of this code is my own, apologies for the fact it is probably a mess and/or horribly written, but my question is why the lines

D = open("C:\\aPATH\\hPROC.txt", "a")
D.write("End") 

aren't appending "End" at the bottom of the file whenever it is called.

import time

def replace_all(text, rps):
    for i, j in rps.items():
        text = text.replace(i, j)
    return text

def replacer():
    inf = "hScrape.txt"
    ouf = "hPROC.txt"
    A = open(inf, "r")
    B = open(ouf, "w")
    reps = {"Result Date:":"", "Draw Result:":"", "Bonus":"", "January":"", "February":"", "March":"", "April":"", "May":"", "June":"", "July":"", "August":"", "September":"", "October":"", "November":"", "December":"", "With Max Millions!":"", "2009":"", "2010":"", "2011":"", "2012":"", "2013":"", "2014":"", "2015":"", "2016":"", "2017":"", "2018":"", "30th":"", "29th":"", "28th":"", "27th":"", "26th":"", "25th":"", "24th":"", "23rd":"", "22nd":"", "21st":"", "20th":"", "19th":"", "18th":"", "17th":"", "16th":"", "15th":"", "14th":"", "13th":"", "12th":"", "11th":"", "10th":"", "9th":"", "8th":"", "7th":"", "6th":"", "5th":"", "4th":"", "3rd":"", "2nd":"", "1st":"", "\t":""}
    txt = replace_all(A.read(), reps)
    B.write(txt)
    A.close
    B.close

    D = open("C:\\aPATH\\hPROC.txt", "a")
    D.write("End")

    C = open("C:\\aPATH\\Result.txt", "w+")
    print("Completed Filtering Sequence")
    time.sleep(3)


    while True:
        B = open("hPROC.txt", "r")
        z = B.readline()
        print(z)
        if "End" in z:
            C.write("DN")
            break
        else:
            if z != "\n":
                if " " not in z:
                    if int(z) < 10:
                        C.write("0" + z)
                    else:
                        C.write(z)

replacer()


Solution 1:[1]

You have forgotten to close the file with D.close()

the close() will close the file, and writes all data which may be lingering in buffers.

If you do not want to close the file, you need to "flush" twice, example

D.flush()
os.fsync(D.fileno())

For the later, please do an import os, this will flush the os buffer for this file.

Solution 2:[2]

The best method I found so far is as follows:

with open("your text file") as f:
    for line in f:
        if "your text to append" in line.rstrip('\r\n'):
           print("Exists!")
           break
    else:
        f.write("your text to append" + "\n")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Edwin van Mierlo
Solution 2 Dharman