0

How to append text into a (file.txt) file in python

Here is my program code:

file = open("file.txt", "a")

aa = 10
bb = 1
cc = 12
xx = 20


try:
    if xx > aa:
        file.write("Yes xx is greater than aa")
        file.close()

    elif xx < aa:
        file.write("No xx is not greater than aa")
        file.close()


    if aa > xx:
        file.write("Yes aa is greater than xx")
        file.close()

    elif aa < xx:
        file.write("No aa is not greater than xx")
        file.close()


    if cc > xx:
        file.write("Yes cc is greater than xx")
        file.close()

    elif cc < xx:
        file.write("No cc is not greater than xx")
        file.close()
except Exception as e:
    print(e)

and the output is:

file

My problem is why is only first if and elif condition work and write that string into text file and rest of condition run successfully but string not append in that file.

I would be very grateful if you could tell me how can I resolve this problem.

ammely
  • 85
  • 1
  • 8

2 Answers2

0

You're closing the file after you write text to it. If you close the file you cannot write to it anymore unless you open it again. If you use the with-statement, it will close the file for you.

Try something like this:

aa = 10
bb = 1
cc = 12
xx = 20

with open("file.txt", "a") as file:
    try:
        if xx > aa:
            file.write("Yes xx is greater than aa")
        elif xx < aa:
            file.write("No xx is not greater than aa")
        if aa > xx:
            file.write("Yes aa is greater than xx")
        elif aa < xx:
            file.write("No aa is not greater than xx")
        if cc > xx:
            file.write("Yes cc is greater than xx")
        elif cc < xx:
            file.write("No cc is not greater than xx")
    except Exception as e:
        print(e)
funie200
  • 3,688
  • 5
  • 21
  • 34
-1

Your problem is that you are closing the file, as soon as you append to it the first time. Removing file.close() and only using it once in the end, will solve your problem. Also a more pythonic way of doing things, would be to use with open("file.txt", "a") as file: Here is my edited version of your code:

aa = 10
bb = 1
cc = 12
xx = 20

with open("file.txt", "a") as file:

    try:
        if xx > aa:
            file.write("Yes xx is greater than aa\n")
            
        elif xx < aa:
            file.write("No xx is not greater than aa\n")
            
        if aa > xx:
            file.write("Yes aa is greater than xx\n")
            
        elif aa < xx:
            file.write("No aa is not greater than xx\n")    

        if cc > xx:
            file.write("Yes cc is greater than xx\n")
            
        elif cc < xx:
            file.write("No cc is not greater than xx\n")

        file.close()

    except Exception as e:
        print(e)

P.S The \n is a line break. This way it will make the output a little bit tidier.

LeSchlongLong
  • 350
  • 2
  • 8