【问题标题】:Trying to create JSON file with name of XML file and load data from xml file by using Python尝试使用 Python 创建具有 XML 文件名称的 JSON 文件并从 xml 文件加载数据
【发布时间】:2019-12-07 06:00:20
【问题描述】:

尝试创建与 XML 文件同名的 JSON 文件并使用 Python 将 XML 数据转储到该文件中

import os
import json
import xmltodict

# Reading file from directory
with os.scandir('C:/jsonfile/') as entries:
    for entry in entries:
        name=(entry.name)  
        print(name)
        base = os.path.splitext(name)[0] #Getting name of the file
        f= open("C:/jjsonfile/"+base+".json","w+")
        with open("C:/jsonfile/"+name, 'r') as f: #Creating JSON file
            xmlString = f.read()
        jsonString = json.dumps(xmltodict.parse(xmlString), indent=4) 
        with open(f, 'w') as f: #Loading data into JSON file.
            f.write(jsonString)    

1019586313.xml

----------------------------------- ---------------------------- TypeError Traceback(最近一次调用 最后)在 13 xmlString = f.read() 14 jsonString = json.dumps(xmltodict.parse(xmlString), 缩进=4) ---> 15 with open(f, 'w') as f: 16 f.write(jsonString) 17

TypeError: 预期的 str、bytes 或 os.PathLike 对象,不是 _io.TextIOWrapper

【问题讨论】:

  • 尝试做 json.dumps(xmltodict.parse(str(xmlString)), indent=4)
  • 不..!! “not _io.TextIOWrapper”的主要问题

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


【解决方案1】:

当使用open创建json文件时,你需要将你想要创建的文件的路径传递给它,你所做的就是传递对象f,

with open(f, 'w') as f:

这是您使用创建的_io.TextIOWrapper 对象

with open("C:/jsonfile/"+name, 'r') as f

所以为了解决这个问题,你需要将你要创建的 json 文件的名称传递给它,所以你应该这样做

with open("C:/jjsonfile/"+base+".json","w+") as f:

而不是这个

with open(f, 'w') as f:

并删除此行

f= open("C:/jjsonfile/"+base+".json","w+")

【讨论】:

  • 不。没有运气..!!
  • 还是同样的错误?,你到底改了什么?
【解决方案2】:
import os
import json
import xmltodict


with os.scandir('C:/ARP_project/') as entries:
    for entry in entries:
        name=(entry.name)
        print(name)
        base = os.path.splitext(name)[0]
        jsname= "C:/ARP_Json/"+ base+".json" # created Variable for json file name
        f= open(jsname,"w+")
        with open("C:/ARP_project/"+name, 'r') as f:
            xmlString = f.read()
        jsonString = json.dumps(xmltodict.parse(xmlString), indent=4) 
        with open(jsname, 'w') as f:
            f.write(jsonString)  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多