循环只读取文件的第一行

时间:2016-10-15 14:25:47

标签: python json xml loops

我尝试使用小型python脚本将JSON文件转换为XML,但由于某种原因,循环似乎只读取了JSON文件的第一行。

from xml.dom import minidom
from json import JSONDecoder
import json
import sys
import csv
import os
import re
import dicttoxml
from datetime import datetime, timedelta
from functools import partial
reload(sys)
sys.setdefaultencoding('utf-8')

nav = 'navigation_items.bson.json'
df = 'testxmloutput.txt'

def json2xml(json_obj, line_padding=""):
result_list = list()

json_obj_type = type(json_obj)

if json_obj_type is list:
    for sub_elem in json_obj:
        result_list.append(json2xml(sub_elem, line_padding))

    return "\n".join(result_list)

if json_obj_type is dict:
    for tag_name in json_obj:
        sub_obj = json_obj[tag_name]
        result_list.append("%s<%s>" % (line_padding, tag_name))
        result_list.append(json2xml(sub_obj, "\t" + line_padding))
        result_list.append("%s</%s>" % (line_padding, tag_name))

    return "\n".join(result_list)

return "%s%s" % (line_padding, json_obj)

def json_parse(fileobj, decoder=JSONDecoder(), buffersize=2048):
buffer = ''
for chunk in iter(partial(fileobj.read, buffersize), ''):
     buffer += chunk
     while buffer:
         try:
             result, index = decoder.raw_decode(buffer)
             yield result
             buffer = buffer[index:]
         except ValueError:
             # Not enough data to decode, read more
             break

def转换器(数据):

f = open(df,'w')
data = open(nav)
for line in json_parse(data):
    f.write(dicttoxml.dicttoxml(line, attr_type=False))

f.close()

converter(nav)

我假设iter会将第一行读入内存并继续下一行。转换后的输出看起来很棒,但我也很确定在哪里查看如何让它循环到文件中的下一行。

1 个答案:

答案 0 :(得分:0)

尝试使用json.load将文件加载到dict中,然后迭代输出的dict。

import sys
import json

json_file = sys.argv[1]
data = {}
with open(json_file) as data_file:    
    data = json.load(data_file)

for key in data:
    #do your things