繁体   English   中英

编写基于CSV单元格Python的XML文件名

[英]Write XML filename based of CSV cell Python

尝试将此脚本的输出保存到基于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

我不确定是否要遵循,但如果

  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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM