Я определил функцию и хочу записать ее вывод в текстовый файл. Что мне нужно изменить в своем коде? - PullRequest
3 голосов
/ 12 июля 2011
print "I can write my function to a txt file:"
my_function = raw_input("File name? ")

print_bills = input(bills(1010, 200, 100, 120))

open(my_function, 'w')
my_function.write('%r' % (print_bills))
my_function.close()

Я работаю в Python и пытаюсь записать свою функцию в текстовый файл, функция выглядит следующим образом

def bills(mortgage, elec, oil, ph_int_tv):

    print "Our upcoming mortgage will be approximately %d /month)" % mortgage

    print "Split between my brother and I, that will be %d /month" % (mortgage/2)

    print "With a third roomate, it will be %d /month" % (mortgage/3)

    print "My total bill, per month, with living costs included will be %d /month" % ((mortgage/2)+(elec/2)+(oil/2)+(ph_int_tv/2))

    print "I better start saving money!!\n"

Я довольно новичок, только начал с онлайн-книгой LPTHW ... Итак, мой вопрос: что я могу изменить в верхнем коде, чтобы заставить это работать .... если что?

Ответы [ 3 ]

3 голосов
/ 12 июля 2011

Вы можете переназначить стандартный вывод

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)
0 голосов
/ 12 июля 2011
def bills(mortgage, elec, oil, ph_int_tv):
    print "Our upcoming mortgage will be approximately %d /month)" % mortgage
    print "Split between my brother and I, that will be %d /month" % (mortgage/2)
    print "With a third roomate, it will be %d /month" % (mortgage/3)
    print "My total bill, per month, with living costs included will be %d /month" % ((mortgage/2)+(elec/2)+(oil/2)+(ph_int_tv/2))
    print "I better start saving money!!\n"

def my_function(my_file,print_bills):
    f=open(my_file, 'w')
    f.write('%r' % (print_bills))
    f.close()

print "I can write my function to a txt file:"
my_file = raw_input("File name? ")

print_bills = bills(1010, 200, 100, 120)


my_function(my_file, print_bills)
0 голосов
/ 12 июля 2011

По сути, в Python стандартный вывод может быть обработан (почти) как любой другой файловый объект.Таким образом, вы можете назначить объект файла для sys.stdout, и оператор print будет записан в файл, а не напечатан в окне терминала.

Может работать что-то вроде следующего.

import sys

myfile = open('myfile.txt', 'w')
stdout_bckp = sys.stdout
sys.stdout = myfile
bills(1010, 200, 100, 120)
sys.stdout = stdout_bckp
myfile.close()

Если вы работаете на каком-то Unix-компьютере, вы также можете перенаправить вывод из программы, которую вы запускаете с терминала, следующим образом:

$ python myscript.py > myfile.txt
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...