我正在尝试为 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/