将python函数输出写入.txt文件

平方

所以我有这些功能,旨在将其输出打印/写入文本文件。现在,当这些函数在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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Linux,将输出写入文件并使用Python终止

来自分类Dev

如何执行python脚本并将输出写入txt文件?

来自分类Dev

Python Web Scrape将输出写入文件

来自分类Dev

将列表写入txt文件时被缩短

来自分类Dev

正则表达式Python将输出写入文件

来自分类Dev

无法将csv写入.txt文件?的PHP

来自分类Dev

将行写入.txt文件C ++

来自分类Dev

将网络数据写入TXT文件

来自分类Dev

将列表写入txt文件

来自分类Dev

将字典值(列表)写入输出文件-Python

来自分类Dev

写入txt文件java

来自分类Dev

Python Web Scrape将输出写入文件

来自分类Dev

将所有输出写入文件(Python)

来自分类Dev

将Python输出写入屏幕或文件名

来自分类Dev

如何将Portage的输出写入txt文件?

来自分类Dev

正则表达式Python将输出写入文件

来自分类Dev

Python-将矩阵写入txt文件,保持格式

来自分类Dev

将“ <”或“>”写入.txt文件

来自分类Dev

尝试写入python .txt文件

来自分类Dev

将RegEx结果从多个HTML文件写入.txt输出文件

来自分类Dev

函数不写入 txt 文件

来自分类Dev

在 Python 3 中使用数组将变量写入 txt 文件

来自分类Dev

用 Python 将 XML 格式的文本写入输出文件

来自分类Dev

Python - 将变量输出到 TXT 文件

来自分类Dev

如何将输出写入函数内部的文件?

来自分类Dev

F字符串和将函数输出写入python3中的文件

来自分类Dev

如何更改python程序以将输出写入文件?

来自分类Dev

如何将顶部输出写入python中的文件?

来自分类Dev

Python读取txt文件中的行并写入新的txt文件