python - 如何在 python 3 中替换此语句 "StringIO import StringIO "(在 python 2 中可用)

标签 python xml parsing

显然,我是 Python 的新手。

我想在下面的代码中使用 StringIO :提取 example.xml

 import os
os.chdir('d:/py/xml/')


from lxml import etree
from StringIO import StringIO

#----------------------------------------------------------------------
def parseXML(xmlFile):
    """
    Parse the xml
    """
    f = open(xmlFile)
    xml = f.read()
    f.close()

    tree = etree.parse(StringIO(xml))
    context = etree.iterparse(StringIO(xml))
    for action, elem in context:
        if not elem.text:
            text = 'None'
        else:
            text = elem.text
        print (elem.tag + ' => ' + text)

if __name__ == "__main__":

parseXML("example.xml")

但我一直收到这条消息

语法错误:来自 io import import StringIO:d:\py\xml\example.py,第 621 行 文件“d:\py\xml\example.py”,第 6 行,在 ? 从 io 导入导入 StringIO

我搜索了谷歌,但它说要导入 io 模型并使用 io.StringIO 或 io.BytesIO 来获取文本或数据...

谁能告诉我,我该怎么做?

谢谢

最佳答案

http://docs.python.org/release/3.0.1/whatsnew/3.0.html#text-vs-data-instead-of-unicode-vs-8-bit :

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

从 io 导入 StringIO

关于python - 如何在 python 3 中替换此语句 "StringIO import StringIO "(在 python 2 中可用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12146912/

相关文章:

python - Celery 与 SQS 代理和死信队列

python - Numpy 二维数组,获取指定列索引等于 1 的行的索引

css - OpenERP( View ) - 随着标签和字段之间的空间变化?

android - 在 android XML 上结合多个背景?

python3提取txt文件中两个字符串之间的字符串

python - 在Python中重置(重新初始化)整数列表(至0)的最佳方法是什么

python - 将值从一个 DataFrame 映射到另一个 DataFrame

java - 如何拆分XML?一些例子?

java - Jsoup 查找具有特定文本的元素

php - 在解析网页时删除 javascript 代码