Search code examples
pythonurllib

How can I save parsed xml as txt?


I have parsed XML to list, and I'd like to save this as txt file.

But there's an error..

How can I save it to txt..?

I am a very starter of python, so I don't know how to do.

My xml url is https://pvxml.map.naver.com/api/get?type=xml&pano_id=/c7VUP7/zsr2UT/De2VlQA==&rv=3

And I would like to parse the street_panorama id.

import os
import urllib.request as urllib from xml.dom
import minidom
with open ('list.txt','w') as f:
    f.write('C:/Users/JYLEE/Desktop/python/exercise')
    url = 'https://pvxml.map.naver.com/api/get?type=xml&pano_id=/c7VUP7/zsr2UT/De2VlQA==&rv=3' 
    dom = minidom.parse(urllib.urlopen(url))
    link = dom.getElementsByTagName('street_panorama')
    categories = [items.attributes['id'].value for items in link if items.attributes['id']]
    f.write(categories)

The error message is TypeError: write() argument must be str, not list

I don't know what to do next...


Solution

  • You can just convert the list (categories) into a string format by using the str() method.

    Also, try to use with statements whenever you are trying to read or write a file. If you use read or write commands barely you should close the file after the usage using f.close() command.

    This is taken care automatically if you use with command.

    This is the corrected code of yours for your reference

    import os
    import urllib.request as urllib 
    from xml.dom import minidom
    with open("list1.txt",'w') as f:
        f.write('C:/Users/JYLEE/Desktop/python/exercise')
    
    url = 'https://pvxml.map.naver.com/api/get?type=xml&pano_id=/c7VUP7/zsr2UT/De2VlQA==&rv=3' 
    dom = minidom.parse(urllib.urlopen(url))
    link = dom.getElementsByTagName('street_panorama')
    categories = [items.attributes['id'].value for items in link if items.attributes['id']]
    with open("list1.txt",'w') as f:
        f.write(str(categories))