所以我有这些功能,旨在将其输出打印/写入文本文件。现在,当这些函数在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)
是否有一种简单的方法可以将函数的输出写入文本文件?我已经看到“ >>”运算符四处可见,但似乎无法正常运行。如果需要更多信息,我可以提供。
再次感谢!
在python 3中,您可以print
使用file
关键字将函数的输出重定向到文件:
with open('somefile.txt', 'rt') as f:
print('Hello World!', file=f)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句