I'm new working with Python3 and can't figure out how to save my outputs in a file. I know from other discussion that you can do:
f = open(filename, 'w')
print('whatever', file = f)
but in my case the outputs I want to save are not written in a "print". As you can see below, I'm calling the class "TruieGest" in another file to run a simulation for my different animals (sows['ID']):
def simulation():
for sows['ID'] in sows['ID']:
SowGest = TruieGest(sows['ID'], sows['Age'], sows['Portee'])
SowGest.data_lactation()
return simulation
simulation()
sorties.close()
Any idea on how i can get my outputs in a file ?
Thanks !
Let's say that you are using the interactive Python prompt and that you are using a module, that you cannot completely control/rewrite that outputs its results directly to the screen.
If what you want to do is to save to file some of these outputs (maybe you want to see the results interactively and fiddle with some parameters before committing the results to a file) you can do as follows
15:14 boffi@debian:~ $ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 29 2018, 16:14:56)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> def f(): print('Hi Charlotte!')
>>> f()
Hi Charlotte!
>>> with open('a_file.txt', 'w') as sys.stdout:
... f()
As you can see (if you try my code...) the second function call prints nothing, and we can see the contents of a_file.txt
from the shell
15:16 boffi@debian:~ $ cat a_file.txt
Hi Charlotte!
I guess that this is what you need.
And if you want to know how it works... First you import sys
, that is the standard library module that interacts with the system, and when you want to commit a method output, you temporarily reassign (with the with
statement) the standard output stream (sys.stdout
) to a file object. All the statements that follow in the indented with
block (technically a context manager) will not print to the terminal but to the file. Another nicety, when you dedent your code 1. the file is automatically closed and 2. the print
s are anew connected with the terminal.
PS If you'd like to append different segments of output to the same file, you can. Read about the open
function, that is able to reopen an existing file in append mode.