Python XML 随机赋值

标签 python xml

我正在尝试为 XML 密码标签分配一个随机值。

XML 文件示例。

<database>
 <group>
   <entry>
    <username>root</username>
    <password>XXXXXX</password>
   </entry>
   <entry>
    <username>root</username>
    <password>YYYYY</password>
   </entry>
 </group>
</database>

这是我当前的 python 代码

#!/usr/bin/python3.5

import xml.etree.ElementTree as ET
import random
import string

random = ''.join([random.choice(string.ascii_letters + string.digits + string.punctuation) for n in range(10)])

tree = ET.ElementTree(file='test2.xml')
root = tree.getroot()

for admin in root.findall("./group/entry/[username='root']"):
    password = admin.find('password').text = random
    print(password)

我得到分配的相同随机值。我做错了什么?

最佳答案

您将第一个随机值分配给了 random 变量,然后就再也没有更改过它的值。

为了实现你想要的,你需要计算循环内的随机值:

for admin in root.findall("./group/entry/[username='root']"):
    password = ''.join([random.choice(string.ascii_letters + string.digits + string.punctuation) for n in range(10)])
    print(password)

旁注:你应该避免 shadowing standard library modules命名变量时。

关于Python XML 随机赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35479376/

相关文章:

javascript - 格式化后的日期值返回 'undefined'

xml - 翻译xml文件中的字符串

Python正则表达式通过AND条件查找匹配词

python - 为什么属性包装的成员列表显示意外的值?

python - 如何根据特定条件转换和创建具有0和1的pandas列

python - 如何嵌套 numpy() 的 np.where,或者一个接一个?

xml - 如何在门户网站odoo13上添加所见即所得

python - 可以编写在 Python 和 IronPython 上运行的 XML 读取代码吗?

python - 相当于 Ruby 中 Python 的 findall() 方法?

xml - 我应该把资源实体文件放在~tomcat/目录的什么地方?