Abhideep
Abhideep

Reputation: 11

Trying to create JSON file with name of XML file and load data from xml file by using Python

Trying to create JSON file same name as XML file and dump XML data into that using Python

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 (most recent call last) in 13 xmlString = f.read() 14 jsonString = json.dumps(xmltodict.parse(xmlString), indent=4) ---> 15 with open(f, 'w') as f: 16 f.write(jsonString) 17

TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper

Upvotes: 0

Views: 160

Answers (2)

Abhideep
Abhideep

Reputation: 11

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)  

Upvotes: 0

When using open to create the json file you need to pass it the path to the file you want to create,what you are doing is that you are passing it the object f,

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

which is a _io.TextIOWrapper object that you created with

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

so in order to fix this, you need to pass it the name of the json file you wa to create, so you should do this

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

instead of this

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

and remove this line

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

Upvotes: 0

Related Questions