0
嘗試將此腳本的輸出保存到基於csv中單元格的文件中。我可以調用變量{file_root_name}
來寫入xml文件,但不能作爲寫入文件名的變量。如何使用變量file_root_name
作爲變量來生成文件名?基於CSV單元格寫入XML文件名Python
import csv
import sys
from xml.etree import ElementTree
from xml.etree.ElementTree import Element, SubElement, Comment, tostring
from xml.dom import minidom
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=" ", encoding = 'utf-8')
doctype = '<!DOCTYPE smil PUBLIC "-//W3C//DTD SMIL 2.0//EN" "http://www.w3.org/2001/SMIL20/SMIL20.dtd">'
video_data = ((256, 336000),
(512, 592000),
(768, 848000),
(1128, 1208000))
with open(sys.argv[1], 'rU') as f:
reader = csv.DictReader(f)
for row in reader:
root = Element('smil')
root.set('xmlns', 'http://www.w3.org/2001/SMIL20/Language')
head = SubElement(root, 'head')
meta = SubElement(head, 'meta base="rtmp://cp23636.edgefcs.net/ondemand"')
body = SubElement(root, 'body')
switch_tag = ElementTree.SubElement(body, 'switch')
for suffix, bitrate in video_data:
attrs = {'src': ("mp4:soundcheck/{year}/{id}/{file_root_name}_{suffix}.mp4"
.format(suffix=str(suffix), **row)),
'system-bitrate': str(bitrate),
}
ElementTree.SubElement(switch_tag, 'video', attrs)
xml, doc = prettify(root).split('\n', 1)
output = open('file_root_name'+'.smil', 'w')
output.write(xml + doctype + doc)
output.close
該行可以工作,但是,如果我嘗試'打印file_root_name',我得到'NameError:name'file_root_name'未定義'因此,它在'attrs'內工作時不起作用。 – 2011-12-30 22:25:04
它不起作用,因爲它不是一個變量。 'file_root_name'是行字典中的一個關鍵字,帶有一些相關的值(比如「fred」)。如果你想要一個,只需使用'file_root_name = row [「file_root_name」]'。 – DSM 2011-12-30 22:27:52