我正在嘗試創建一個應用程序來創建一個xml文件,並且我想將文本分配給某些元素。此文本由文件夾上的圖像文件組成。代碼如下:Python - for循環僅輸出最後一次迭代
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,但只與最後一次的路徑,重複任意多次在文件夾中的文件的數目。我想要的是它爲每個「文件」元素打印一個路徑,並在前面的「to」元素和下一個「元素」上打印相同的路徑。也許這是一個我不知道的簡單解決方案。我仍然是一個新手。在每次迭代
在此先感謝
謝謝您的回答。我設法解決它。 – Unkuiri