简体   繁体   English

如何在Python中将(if-else)打印语句的输出重定向到文本文件

[英]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. 我有这段代码,然后将输出打印到txt文件中。 However whenever I open a file, f=open("out.txt",'w') it shows unexpected indent. 但是,每当我打开文件f = open(“ out.txt”,'w')时,它都会显示意外的缩进。 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 在Python3中,输出重定向非常简单

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

Refer the docs 参考文档

In your particular case you can even use the with open syntax as in 在您的特定情况下,您甚至可以使用with open语法,如

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. 注意-如果您要重新执行程序,最好使用'a' (附加)而不是'w'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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