Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python XML随机分配_Python_Xml - Fatal编程技术网

Python XML随机分配

Python XML随机分配,python,xml,Python,Xml,我试图给XML密码标记分配一个随机值 XML文件的示例 <database> <group> <entry> <username>root</username> <password>XXXXXX</password> </entry> <entry> <username>root</username> <pa

我试图给XML密码标记分配一个随机值

XML文件的示例

<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)