如何将解析后的xml保存为txt?

2024-09-29 18:55:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经将XML解析为列表,我想将其保存为txt文件

但是有个错误

如何将其保存到txt

我是python的初学者,所以我不知道怎么做

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

我想解析街道全景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)

错误消息是TypeError: write() argument must be str, not list

我不知道下一步该怎么办


Tags: httpsimporttxtcomidurlmap错误
2条回答

您可以使用str()方法将列表(categories)转换为字符串格式

另外,当您试图readwrite一个文件时,尝试使用with语句。如果您使用readwrite命令,则应该在使用f.close()命令后关闭文件

如果您使用with命令,这会自动处理

这是你的更正代码供你参考

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))

正如消息所说,它需要传递一个字符串。只需执行write(str(categories))即可获得类似于['a', 'b', 'c'][1, 2, 3]的表示。如果您希望每一个都位于新行或某种特定格式上,请循环categories并逐项写入文件

相关问题 更多 >

    热门问题