2

我想从每个组中编写不同的文本文件;我该怎么做?目前它正在将所有内容写入一个txt文件。

data = json.loads(output)
print "===========================Example 1======================================="
for issue in data["issues"]:
    print issue ['key'], issue['fields']['summary']

data = json.loads(output1)
print"======================Example 2===================================="
for issue in data["issues"]:
   print issue ['key'], issue['fields']['summary']

data = json.loads(output2)
print"====================== Example 3===================================="
for issue in data["issues"]:
    print issue ['key'], issue['fields']['summary']

data = json.loads(output3)
print"======================Example 4===================================="
for issue in data["issues"]:
    print issue ['key'], issue['fields']['summary']    

data = json.loads(output4)
print"======================Example 5===================================="
for issue in data["issues"]:
    print issue ['key'], issue['fields']['summary']    

Thia 是我解决这个问题的方法:

for issue in data["issues"]:
   f.write(issue ['key'])
   f.write(issue['fields']['summary']) 
   f.write('\n')

它将每件事都写在一个列表和每一行下的单独文件中。

4

1 回答 1

1

您只是在打印,而不是在您的示例中写入文件。另外,如果有 100 个输出,你会怎么做?

简化解决方案的伪代码示例:

output1 = {...}
outputs = (output1, output2, output3)

for index, output in enumerate(outputs):
    filename = 'output_data_{0}'.format(index)

    #this will write file in directory relative to script location
    with open(filename, 'w') as f:
        f.write('Example {0}:\r\n'.format(index))

        for issue in data["issues"]:
            # assumes issue is of type dict
            # assumes issues has appropriate keys
            # assumes values are of string type
            key = issue['key']
            summary = issue['fields']['summary']

            f.writelines((key, summary, "\r\n",))

对于 Python 文件对象文档:

http://docs.python.org/2/library/functions.html?highlight=open#file http://docs.python.org/2/library/stdtypes.html#bltin-file-objects

另外,请注意,此解决方案不是类型安全的,应注意确保将字符串传递给文件对象的 write 方法。

于 2013-07-22T18:44:36.700 回答