Icey370
Icey370

Reputation: 15

Output Multiple lines to file in Python 2.7.3

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!

Upvotes: 1

Views: 489

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

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.

Upvotes: 1

user3760874
user3760874

Reputation: 77

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

Upvotes: -1

Related Questions