基于CSV-cell-Python编写XML文件名

2024-10-01 07:45:26 发布

您现在位置: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

Tags: csvnamefromimportforstringrootxml
1条回答
网友
1楼 · 发布于 2024-10-01 07:45:26

我不确定我是否会遵守,但是如果

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

works则“file_root_name”必须是dictlike对象行的字符串键。线

^{pr2}$

实际上,文件名与'em'组合在一起。所以你真的想要

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

顺便说一句,排队

^{4}$

不会做任何你想做的事输出.关闭()或者干脆

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

相关问题 更多 >