Abhay Salvi
Abhay Salvi

Reputation: 1129

How to fix adding two outputs of functions and then implementing the combined output to a text file in Python?

I have been trying to combine 2 function's output all together and then printing the combined output of the functions in a text file. But the problem is that i am getting several errors, and if there is no error then it shows the output of one function only. Please fix this thing...

pyhtml.py

    import sys
    sys.setrecursionlimit(1500)


    def text(a):
        with open("index.txt", "w+") as s:
            s.write("<html>\n <h1>" + a + "</h1>\n</html>")


    def para(a):
        with open("index.txt", "w+") as x:
            x.write("\n <p1>" + a + "</p1>\n")

index.py

    from pyhtml import *

    text("hello")
    para("hello")

Please try to combine the output of these two functions in the index.txt file. In my case only one output is showing...

Upvotes: 1

Views: 62

Answers (1)

milanbalazs
milanbalazs

Reputation: 5329

You should change the w+ to a as append instead of write.

The w+ overwrites the file in every open but a creates the file if it does not exist and if it exists a appends the text into it.

In your case:

with open("index.txt", "a") as s:

Content of index.txt:

<html>
 <h1>hello</h1>
</html>
 <p1>hello</p1>

Upvotes: 2

Related Questions