【问题标题】:Writing python function outputs to .txt file将python函数输出写入.txt文件
【发布时间】:2015-01-21 12:55:55
【问题描述】:

所以我有这些函数用于将它们的输出打印/写入文本文件。现在,当这些函数在 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 python-3.x function file output


    【解决方案1】:

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

    或者,您可以使用赋值sys.stdout = outfile 使标准输出指向outfile。这将导致对print 的所有后续调用写入outfile

    【讨论】:

      【解决方案2】:

      在 python 3 中,您可以将 print 函数的输出重定向到带有 file 关键字的文件:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多