简体   繁体   中英

Writing python function outputs to .txt file

So I have these functions that are meant to print/write their outputs to a text file. Now when have these functions print their output in the python shell, I get what I need. It's when I try to have those outputs written to the text file, things go awry.

Here are the functions in particular:

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))

The code I have in the main() function that writes to the text file looks like :

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)

Is there a simple way to have the outputs of the functions written to a text file? I've seen the ">>" operator floating around but I can't seem to get it to work. If more information is required, I can provide it.

Thanks again!

You need to change the calls to print in the functions to outfile.write as well, or use the print(..., file=outfile) syntax.

Alternatively, you can make the standard output point to outfile using an assignment sys.stdout = outfile . That will cause all subsequent calls to print to write to outfile .

in python 3 you can redirect the output of print function to a file with file keyword :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM