Python多个打印输出需要存储在多个文本文件中

时间:2018-03-20 07:07:25

标签: python python-3.x python-2.7

使用API​​,我试图从门户网站获取一些事件数据。从门户网站我得到多个事件输出。我编写了一个脚本来在文本文件中编写打印输出。我的问题是,目前所有事件输出都存储在一个文本文件中,我想根据每个事件将其存储到多个文本文件中。我目前的代码如下:

orig_stdout = sys.stdout
f = open ('alerts.txt', 'w')
sys.stdout = f

#print data

for i in data['alert']:
        print "Alert ID:  " + str(i['alertId'])
        print "Alarm Time:  " + i['dateStart']
        print "Test Name:  " + i['testName']
        print "URL:  " + i['permalink']
        print "Rule ID: " + str(i['ruleId'])
        print "Rule Name: " + i['ruleName']
        print "Test ID: " + str(i['testId'])
        print "Test Name: " + i['testName']
        print "\n"

sys.stdout = orig_stdout
f.close()

2 个答案:

答案 0 :(得分:0)

这应该有所帮助。

for i in data['alert']:                                          #Iterate over your incident 
    with open("{0}.txt".format(i['alertId']), "w") as infile:        #Create file with incident id as name
        infile.write("Alert ID: {}".format(str(i['alertId'])))   #Write content. 
        infile.write("Alert Time: {}".format(i['dateStart']))

答案 1 :(得分:0)

最好制作自定义日志功能。

def myprint(f, *args):
    print(" ".join(map(str,args)), file=f)


var1 = [1,2,3]
var2 = 'testing'
f1= open('log1.txt', 'a')
f2= open('log2.txt', 'a')
myprint(f1, 'this is a', var1, var2)
myprint(f2, 'this is a', var1, var2)

f1.close()
f2.close()

def myprint2( *args):
    f1 = open('log1.txt', 'a')
    f2 = open('log2.txt', 'a')
    print(" ".join(map(str,args)), file=f1)
    print(" ".join(map(str,args)), file=f2)
    print(" ".join(map(str,args)))
    f1.close()
    f2.close()

def myprint3(filename, *args):
    f1 = open(filename, 'a')
    print(" ".join(map(str,args)), file=f1)
    print(" ".join(map(str,args)))
    f1.close()