2

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 !

Charlotte
  • 49
  • 6
  • 1
    Possible duplicate of [Redirect stdout to a file in Python?](https://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python) – vishal Jul 06 '18 at 12:47
  • Why not write them to a file just prior to the return statement? – Matt Cremeens Jul 06 '18 at 12:47
  • 1
    You can use `f.write('whatevs')` and `f.close()` instead of print(). – meissner_ Jul 06 '18 at 12:47
  • Perhaps provide us with the contents of `data_lactation()`. I'm willing to bet you could write something to a file within there. – Matt Cremeens Jul 06 '18 at 12:48
  • Thank you. But i'm a bit lost on what I should put inside de f.write() : the variables I want to print are not defined in the main file as they are in the class file and apparently I can't juste write f.write(simulation). – Charlotte Jul 06 '18 at 12:52
  • I second [serbia99](https://stackoverflow.com/users/8370670/serbia99)'s [comment](https://stackoverflow.com/questions/51210773/python3-class-and-simulation-outputs-in-a-txt-file#comment89402255_51210773). Charlotte, read the [first answer](https://stackoverflow.com/a/4675744/2749397) and ask another question if there is anything in it that you do not understand. – gboffi Jul 06 '18 at 13:03
  • There are some problems in your code: your `simulation` function returns the function itself, which is probably not what you want. If you just want to return without returning a value, you can remove this line. Also, `for sows['ID'] in sows['ID']:` will iterate on `sows['ID']`, if it happens to be possible, and leave it updated with the last value it took in the loop. Again, this is certainly not what you want. I don't know the rest of the code, but you probably need something more like `for sow in sows: SowGest = TruieGest(sow['ID'], ...) – Thierry Lathuille Jul 06 '18 at 13:10
  • More information about data_lactation:
    def data_lactation(self):
    for jour in range(1,125):
    Pu = ….. # several equations to calculate A prop and B prop
    Aprop = (max(x, 0))
    Bprop = 1 – Aprop
    print("day =", jour,"then proportion of A = ", Aprop*100, "and proportion of B = ", Bprop*100)
    jour = jour + 1
    – Charlotte Jul 06 '18 at 13:18
  • OH! I forgot to mention, if you want a permanent record of your interaction with the interpreter NOTHING beats the [Jupyter notebook](https://jupyter.org). – gboffi Jul 06 '18 at 13:40

2 Answers2

0

You should use f.writeline() or f.write().

About the line

TruieGest(sows['ID'], sows['Age'], sows['Portee'])

I believe the easyest thing would be converting this to String, but maybe the methods above handle dict or lists.

(sorry, can't check this right now)

Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
Breno Baiardi
  • 99
  • 1
  • 16
0

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 prints 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.

gboffi
  • 22,939
  • 8
  • 54
  • 85