2011-12-30 82 views
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 

回答

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') 

實際上結合了 '.smil' 的 'file_root_name'。所以,你真的要像

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

BTW,行

output.close 
anything--你想output.close(

不會做)來代替,或者乾脆

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

該行可以工作,但是,如果我嘗試'打印file_root_name',我得到'NameError:name'file_root_name'未定義'因此,它在'attrs'內工作時不起作用。 – 2011-12-30 22:25:04

+1

它不起作用,因爲它不是一個變量。 'file_root_name'是行字典中的一個關鍵字,帶有一些相關的值(比如「fred」)。如果你想要一個,只需使用'file_root_name = row [「file_root_name」]'。 – DSM 2011-12-30 22:27:52