[英]Writing python function outputs to .txt file
因此,我具有這些功能,旨在將其輸出打印/寫入文本文件。 現在,當這些函數在python shell中打印其輸出時,我便得到了所需的東西。 當我嘗試將這些輸出寫入文本文件時,事情變得不對勁了。
具體功能如下:
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)
有沒有簡單的方法可以將函數的輸出寫入文本文件? 我曾經看到過“ >>”運算符,但似乎無法正常運行。 如果需要更多信息,我可以提供。
再次感謝!
您還需要將函數中的print
調用更改為outfile.write
,或使用print(..., file=outfile)
語法。
另外,您也可以使標准輸出點outfile
使用賦值sys.stdout = outfile
。 這將導致所有后續print
調用寫入outfile
。
在python 3中,您可以將print
函數的輸出重定向到具有file
關鍵字的file
:
with open('somefile.txt', 'rt') as f:
print('Hello World!', file=f)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.