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

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

我有这段代码,并将输出打印到一个txt文件中。 但是每当我打开一个文件时, f=open("out.txt",'w') 它显示意外的缩进。我想我把代码行放在了错误的位置。 谁能帮忙。

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

在Python3中输出重定向就像

一样简单
print(....., file = open("filename",'w'))

参考docs

在您的特定情况下,您甚至可以使用 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])

注意 - 最好使用 'a'(追加)而不是 'w',以防重新执行程序。