Python 2.6.1:预期路径分隔符([) [英] Python 2.6.1 : expected path separator ([)

查看:134
本文介绍了Python 2.6.1:预期路径分隔符([)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python 2.6.1中遇到路径分隔符错误。我在python 2.7.2版本中未发现此问题,但是不幸的是,我仅在2.6.1中需要此问题。还有其他方法可以达到相同目的吗? :(

I am getting a path separator error in python 2.6.1. I have not found this issue with python 2.7.2 version, but unfortunately I need this in 2.6.1 only. Is there any another way to achieve the same? :(

我的代码:-

import xml.etree.ElementTree as ET #version 1.2.6
import sys   

class usersDetail(object): 

    def __init__(self, users=None):
        self.doc = ET.parse("test.xml")
        self.root = self.doc.getroot()

    def final_xml(self,username):
        r = self.root.find("user[@username='user1']") #not working in 2.6.1 :(
        self.root.remove(r)
        print r
        tree = ET.ElementTree(self.root)
        tree.write("msl.xml") 

if __name__ == '__main__':
    parser = usersDetail()
    parser.final_xml("user1") 

test.xml是:-

test.xml is :-

<?xml version="1.0"?>
<users>
<user afp="yes" cifs="yes"  username="user1" volume="vol" webdev="yes" /></user>
</users>

此操作将仅在以下情况下删除xml:用户名=用户名。预先感谢您的宝贵时间。

What this will do is it will remove the xml only if username = username. Thanks in advance for your valuable time.

推荐答案

您正在使用XPath表达式,<$ c $不支持该表达式Python 2.6中包含的c> ElementTree 版本。在 .findall()之后,您需要手动过滤属性:

You are using an XPath expression, that is not supported by the ElementTree version included in Python 2.6. You'll need to filter for the attribute manually, after a .findall():

def final_xml(self,username):
    users = self.root.findall("user")
    for user in users:
        if user.attrib.get('username') == 'user1':
            break
    else:
        raise ValueError('No such user')

    # `user` is now set to the correct element
    self.root.remove(user)
    print user
    tree = ET.ElementTree(self.root)
    tree.write("msl.xml") 

这篇关于Python 2.6.1:预期路径分隔符([)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆