根据CSV cell Python编写XML文件名

时间:2011-12-30 22:12:08

标签: python csv

尝试将此脚本的输出保存到基于csv中的单元格的文件中。我可以调用变量{file_root_name}来写入xml文件,但不能作为写入文件名的变量。如何使用变量file_root_name作为变量来生成文件名?

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

1 个答案:

答案 0 :(得分:1)

我不确定我会遵循,但是如果该行

  attrs = {'src': ("mp4:soundcheck/{year}/{id}/{file_root_name}_{suffix}.mp4"
                             .format(suffix=str(suffix), **row)),
                     'system-bitrate': str(bitrate),
                     }

工作,然后“file_root_name”必须是dictlike对象行的字符串键。这条线

    output = open('file_root_name'+'.smil', 'w')

实际上将字符串'file_root_name'与'.smil'组合在一起。所以你真的想要像

这样的东西
    output = open(row['file_root_name']+'.smil', 'w')

BTW,该行

    output.close

不会做任何事情 - 你想要输出output.close(),或者只是

with open(row['file_root_name']+'.smil', 'w') as output:
    output.write(xml + doctype + doc)