Output Multiple lines to file in Python 2.7.3

501 views Asked by At

I'm currently writing a program in python with pyCLIPS.

The clips module allows me to print multiple lines of output into the terminal simply by using: clips.PrintFacts()

However, I would like to output this to a file to save results. I am using the following code:

def Print():    
    f1=open('/var/log/combined/test.log', 'a')
    print >>f1, '- Facts -\n'
    print >>f1, clips.PrintFacts()
    print >>f1, '\n- Rules -\n'
    print >>f1, clips.Print.Rules()

the 1st and 3rd print commands successfully print their strings to the file but the 2nd and 4th print commands still only output the clips results into the terminal. Below is an example of the output:

============

root@ubuntu:/home/user/Desktop# python program.py
f-0    (initial-fact)
f-1    (duck)
f-2    (quack)
For a total of 3 facts.
MAIN:
Rule1
Rule2
Rule3
Rule4
Rule5
root@ubuntu:/home/user/Desktop# cat /var/log/combined/test.log
 - Facts -
None
 - Rules -
None
root@ubuntu:/home/user/Desktop#

============

The clips.PrintFacts() section starts at "f-0" whereas the clips.PrintRules() starts at "MAIN".

thanks in advance!

2

There are 2 answers

11
Padraic Cunningham On BEST ANSWER

Use a to append to the file:

f1 = open('/var/log/combined/test.log', 'a+')
print >>f1, clips.PrintFacts()

You are overwriting each line using w.

0
user3760874 On

(This answer is very spontaneous and I don't know if it's true, I just have an idea.)

I think it writes every line but then writes another line on top of it. You should save everything to a string (string = string + clips.printFacts()) and then save that to the file.