Python XML随机分配
我试图给XML密码标记分配一个随机值 XML文件的示例Python XML随机分配,python,xml,Python,Xml,我试图给XML密码标记分配一个随机值 XML文件的示例 <database> <group> <entry> <username>root</username> <password>XXXXXX</password> </entry> <entry> <username>root</username> <pa
<database>
<group>
<entry>
<username>root</username>
<password>XXXXXX</password>
</entry>
<entry>
<username>root</username>
<password>YYYYY</password>
</entry>
</group>
</database>
我得到了相同的随机值。我做错了什么?您应该将随机值的生成移动到循环中,以便每次生成一个新值
#!/usr/bin/python3.5
import xml.etree.ElementTree as ET
import random
import string
tree = ET.ElementTree(file='test2.xml')
root = tree.getroot()
chars = string.ascii_letters + string.digits + string.punctuation
for admin in root.findall("./group/entry/[username='root']"):
rand = ''.join([random.choice(chars) for n in range(10)])
password = admin.find('password').text = rand
print(password)
此外,在命名变量<代码>随机< /代码>时,你要重写包<代码>随机导入,这是不好的做法,考虑把你的变量名改成别的东西。
< p>你把第一个随机值赋值给<代码>随机< /代码>变量,然后从未改变它的值。p> 为了实现您想要的,您需要计算循环中的随机值: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)
另请注意:在命名变量时应避免使用
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)