2014-11-23 54 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