2014-11-23 202 views
0

所以我有这些函数是打印/输出到文本文件的输出。现在,当这些函数在python shell中输出它们的输出时,我得到了我所需要的。当我试图将这些输出写入文本文件时,事情就会出错。将python函数输出写入.txt文件

下面是功能具体为:

def printsection1(animals, station1, station2): 
    for animal in animals: 
     print(animal,'     ',station1.get(animal, 0),'     ',station2.get(animal, 0)) 

def printsection2(animals, station1, station2): 
    for animal in animals: 
     if station2.get(animal, 0)+station1.get(animal, 0) >= 4: 
      print(animal) 

def printsection3(animals, station1, station2): 
    for animal in animals: 
     print(animal,'     ',int(station1.get(animal, 0))+int(station2.get(animal, 0))) 

def printsection4(items): 
    import statistics 
    most_visits=[] 
    for animal, date, station in items: 
     most_visits.append(date[0:2]) 

    print(statistics.mode(most_visits)) 

我在main()函数写入文本文件看起来类似的代码:

outfile.write("Number of times each animal visited each station:\n") 
outfile.write("Animal ID   Station 1   Station 2 \n") 
printsection1(animals, station1, station2) 
outfile.write('\n') 
outfile.write("============================================================ \n") 

outfile.write("Animals that visited both stations at least 4 times \n") 
printsection2(animals, station1, station2) 
outfile.write('\n') 
outfile.write("============================================================ \n") 

outfile.write("Total number of visits for each animal \n") 
printsection3(animals, station1, station2) 
outfile.write('\n') 
outfile.write("============================================================ \n") 

outfile.write("Month that has the highest number of visits to the stations \n") 
printsection4(items) 

有没有一种简单的方法来将函数的输出写入文本文件?我已经看到“>>”运算符在浮动,但我似乎无法使其工作。如果需要更多信息,我可以提供。

再次感谢!

回答

1

在Python 3,你可以print函数的输出重定向到一个文件file关键字:

with open('somefile.txt', 'rt') as f: 
    print('Hello World!', file=f) 
2

您还需要将功能中的print更改为outfile.write,或使用print(..., file=outfile)语法。

或者,您可以使用作业sys.stdout = outfile将标准输出点设置为outfile。这将导致所有后续调用print写入outfile

+0

谢谢! sys.stdout函数取得了诀窍! – Ksquared 2014-11-24 03:09:30