繁体   English   中英

在Python 2.7.3中将多行输出到文件

[英]Output Multiple lines to file in Python 2.7.3

我目前正在使用pyCLIPS在python中编写程序。

clips模块允许我简单地使用以下命令将多行输出打印到终端中:clips.PrintFacts()

但是,我想将此输出到文件以保存结果。 我正在使用以下代码:

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

第1和第3打印命令成功将其字符串打印到文件中,但是第2和第4打印命令仍仅将剪辑结果输出到终端。 以下是输出示例:

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

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#

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

clips.PrintFacts()部分从“ f-0”开始,而clips.PrintRules()从“ MAIN”开始。

提前致谢!

使用a附加到文件:

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

您正在使用w覆盖每一行。

(这个答案很自然,我不知道这是不是真的,我只是有一个主意。)

我认为它会写每一行,然后在其上面再写一行。 您应该将所有内容保存到字符串(字符串=字符串+ clips.printFacts()),然后将其保存到文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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