简体   繁体   中英

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])

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM