Json文件只附加了第一个python脚本

时间:2017-06-29 15:40:31

标签: python json python-2.7

我有一个运行在目录中的python脚本,搜索字符串并在读取字符串时打印出文件和行

for check_configs in glob.glob('/etc/ansible/logs/*.txt'):
    with open(check_configs) as f:
        for line in f:
            #find which line string occurs
            data = []
            if 'test' in line:
                data.append({'File':check_configs,'Line':line})
                print data
                #print file and line in json file
                with open('/etc/ansible/results/get_ip_check', 'w') as outfile:
                    json.dump(data, outfile, indent=4)      
            else:
                #if not in line continue to next line/file
                continue

出于调试目的,我已经包含了行打印数据来打印我得到的内容。每次出现字符串时都会打印出来,

[{'Line': 'test\n', 'File': '/my/test/dir/logs/log2.txt'}]

[{'Line': 'test other test config\n', 'File': '/my/test/dir/logs/log1.txt'}]

但是json文件只打印出一个字符串

[
    {
        "Line": "test\n", 
        "File": "/my/test/dir/logs/log1.txt"
    }
]

我错过了json循环的东西吗?

2 个答案:

答案 0 :(得分:3)

因为你每次都在循环中打开文件,只是从当前迭代中转储值,覆盖以前发生的任何事情。

你应该在循环开始之前定义data,并在循环结束后移动open并转储到,以便数据在循环中累积,你只需写一次。

(另请注意,else: continue毫无意义,因为无论如何都会发生这种情况;删除这些行。)

data = []
for check_configs in glob.glob('/etc/ansible/logs/*.txt'):
    with open(check_configs) as f:
        for line in f:
            if 'test' in line:
                data.append({'File':check_configs,'Line':line})

with open('/etc/ansible/results/get_ip_check', 'w') as outfile:
    json.dump(data, outfile, indent=4)   

答案 1 :(得分:3)

您将data重置为每个循环中的空列表[]。你必须将它移出循环:

for check_configs in glob.glob('/etc/ansible/logs/*.txt'):
    with open(check_configs) as f:
        data = []   # We create the empty data once before the loop
        for line in f:
            #find which line string occurs
            if 'test' in line:
                data.append({'File':check_configs,'Line':line})
                print data
                #print file and line in json file

            else:
                #if not in line continue to next line/file
                continue

with open('/etc/ansible/results/get_ip_check', 'w') as outfile:
    json.dump(data, outfile, indent=4)