dipayan
dipayan

Reputation: 126

How to redirect the output of print statement of (if-else) to a text file in Python

I have this piece of code, and print the output to a txt file. However whenever I open a file, f=open("out.txt",'w') it shows unexpected indent. I guess I am placing the line of code to a wrong position. Can anyone help.

if(cp<0):

    print("No Common Predecessor")
elif (posa < posb):

    if(posa<0):
        posa=0
    print("Common Predecessor: %s" %n[posa])
else:

    if(posb < 0):
        posb=0
    print("Common Predecessor: %s" %m[posb])

Upvotes: 0

Views: 3457

Answers (1)

Bhargav Rao
Bhargav Rao

Reputation: 52181

In Python3 the output redirection is as simple as

print(....., file = open("filename",'w'))

Refer the docs

In your particular case you can even use the with open syntax as in

if(cp<0):

    print("No Common Predecessor")
elif (posa < posb):

    if(posa<0):
        posa=0
    with open('out.txt','w')as f:
        print("Common Predecessor: %s" %n[posa])
        f.write("Common Predecessor: %s" %n[posa])
else:

    if(posb < 0):
        posb=0
    with open('anotherout.txt','w')as f:
        print("Common Predecessor: %s" %m[posb])
        f.write("Common Predecessor: %s" %m[posb])

Note - It is always better to use 'a' (append) instead of 'w' incase you are re-executing the program.

Upvotes: 2

Related Questions