def walkdir(dirname,node,document): #对目录递归遍历,这里用os.path.walk更简单 for file in os.listdir(dirname): if os.path.isfile(os.path.join(dirname,file)): newFileEl=document.createElement('file') newFileEl.attributes['name']=file.encode('utf8') node.appendChild(newFileEl) elif os.path.isdir(os.path.join(dirname,file)): newFileEl=document.createElement('dir') newFileEl.attributes['name']=file.encode('utf8') node.appendChild(newFileEl) walkdir(os.path.join(dirname,file),newFileEl,document) walkdir(dirname,rootdir,newdoc) return newdoc
if __name__ == '__main__': if len(sys.argv)<3: usage() sys.exit() if not os.path.isdir(sys.argv[1]): print 'Error:',sys.argv[1],'is not a directory.' sys.exit() xmlfile=file(sys.argv[2],'w')
def xml2dir(xmlElement,dirname): """由xml文档生成目录 xml2dir(xmlElement,dirname) xmlElement是xml文档元素,标签名file表示文件,dir表示目录。属性name表示文件或目录名 dirname是保存xmlElement整个节点的目录名,将在dirname目录中开始建立xmlElement目录树。""" if not os.path.exists(dirname): os.mkdir(dirname) cwd=os.getcwd() os.chdir(dirname) for childNode in xmlElement.childNodes: if childNode.nodeType not in (childNode.ELEMENT_NODE,childNode.DOCUMENT_NODE): continue if childNode.tagName == u'file': file(childNode.attributes['name'].value,'w').close() elif childNode.tagName == u'dir': if not os.path.exists(childNode.attributes['name'].value): os.mkdir(childNode.getAttribute('name')) xml2dir(childNode,childNode.getAttribute('name')) os.chdir(cwd)
if __name__ == '__main__': if len(sys.argv)<3: usage() sys.exit() try: xmlfile=file(sys.argv[1],'r') except: sys.stderr.write("XML file not found or cannot access.") sys.exit() xmldoc=pydom.parse(xmlfile) xml2dir(xmldoc,os.path.normpath(sys.argv[2].strip())) xmlfile.close()