首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环只读取第一行文件。

循环只读取第一行文件。
EN

Stack Overflow用户
提问于 2016-10-15 14:25:47
回答 1查看 449关注 0票数 0

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

代码语言:javascript
复制
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转换器(数据):

代码语言:javascript
复制
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会将第一行读入内存,然后转到下一行。转换后的输出看起来很棒,但是我太确定如何让它循环到文件中的下一行。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-15 14:54:50

尝试json.load将文件加载到dict中,然后对输出进行迭代。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40060211

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档