Вы можете переназначить стандартный вывод
imporst sys
f = open("test.txt", "w")
sto = sys.stdout # save stdout so we can revert back to it
sys.stdout = f # from now on, anything that is printed will go to test.txt
# here, call any method that calls print
# or even
print "hello"
#finally when no more redirection is desired
f.close()
sys.stdout = sto # reestablish the regular stdout
В этом StackOverflow-вопросе вы также можете найти полезные советы для немного другой цели.Имейте в виду, что некоторые решения могут применяться только к Unix-системам.
Теперь, когда уловка, показанная выше, является целесообразным способом перенаправления вывода консоли (и / или stderr, BTW),и в то время как «что я могу изменить в верхнем коде, чтобы заставить это работать» в вопросе намекало на такой подход перенаправления.Вы можете переписать метод bills () , передав ему файл, вызвав его либо с sys.stdout, либо с файлом по вашему выбору.Что-то вроде:
from __future__ import print_function # might as well get used to Python 3.0 print syntax
def bills(outFile, mortgage, elec, oil, ph_int_tv):
print("Our upcoming mortgage will be approximately %d /month)" % mortgage, file=outFile)
print("Split between my brother and I, that will be %d /month" % (mortgage/2), file=outFile)
print("With a third roomate, it will be %d /month" % (mortgage/3), file=outFile)
print("My total bill, per month, with living costs included will be %d /month"
% ((mortgage/2)+(elec/2)+(oil/2)+(ph_int_tv/2)), file=outFile)
print("I better start saving money!!\n", file=outFile)