gpt4 book ai didi

Python - for循环仅输出最后一次迭代

转载 作者:行者123 更新时间:2023-11-30 23:39:52 25 4
gpt4 key购买 nike

我正在尝试创建一个应用程序来创建 xml 文件,并且我想将文本分配给某些元素。此文本包含文件夹中的图像文件。代码如下:

    import glob
import os
import os.path

from xml.etree import ElementTree
from xml.dom import minidom
import xml.etree.ElementTree as ET

def prettify(elem):
"""Return a pretty-printed XML string for the Element.
"""
rough_string = ElementTree.tostring(elem, 'utf-8')
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ")

path = "/home/unkuiri/Ubuntu One/Wallpapers/*"


background = ET.Element('background')
starttime = ET.SubElement(background, 'starttime')
year = ET.SubElement(starttime, 'year')
month = ET.SubElement(starttime, 'month')
day = ET.SubElement(starttime, 'day')
hour = ET.SubElement(starttime, 'hour')
minute = ET.SubElement(starttime, 'minute')
second = ET.SubElement(starttime, 'second')
static = ET.SubElement(background, 'static')
duration_stat = ET.SubElement(static, 'duration')
files = ET.SubElement(static, 'file')
transition = ET.SubElement(background, 'transition')
duration_trans = ET.SubElement(transition, 'duration')
from1 = ET.SubElement(transition, 'from')
to = ET.SubElement(transition, 'to')

dirList = glob.glob(path)

while len(background.findall("./static/file")) <= len([name for name in os.listdir('.') if os.path.isfile(name)]):
background.append(static)
background.append(transition)
continue

for fname in dirList:

to.text = fname
files.text = fname
from1.text = fname


print prettify(background)

此代码输出格式正确的 xml,但仅包含最后一个路径,重复次数与文件夹中文件的数量相同。我想要的是它为每个"file"元素打印一个路径,并在前面的“到”元素​​和下一个“元素”上打印相同的路径。也许这是一个我不知道的简单解决方案。我还是个新手。

提前致谢

最佳答案

您只需创建一个元素并多次添加同一个元素

在 for 循环中,您会一遍又一遍地分配该元素的成员,因此最终只会得到最后一个 fname

您需要创建一个新元素并每次在 for 循环中填充它

也许你应该有更多类似这样的东西

background = ET.Element('background')
dirList = glob.glob(path)

for fname in dirList:

starttime = ET.SubElement(background, 'starttime')
year = ET.SubElement(starttime, 'year')
month = ET.SubElement(starttime, 'month')
day = ET.SubElement(starttime, 'day')
hour = ET.SubElement(starttime, 'hour')
minute = ET.SubElement(starttime, 'minute')
second = ET.SubElement(starttime, 'second')
static = ET.SubElement(background, 'static')
duration_stat = ET.SubElement(static, 'duration')
files = ET.SubElement(static, 'file')
transition = ET.SubElement(background, 'transition')
duration_trans = ET.SubElement(transition, 'duration')
from1 = ET.SubElement(transition, 'from')
to = ET.SubElement(transition, 'to')

to.text = fname
files.text = fname
from1.text = fname

关于Python - for循环仅输出最后一次迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13149523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com