栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

os.walk()python:目录结构的xml表示,递归

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

os.walk()python:目录结构的xml表示,递归

我建议您不要使用

os.walk()
,因为您必须做很多事情来按摩其输出。所以,应该使用递归函数使用
os.listdir()
os.path.join()
os.path.isdir()
,等。

import osfrom xml.sax.saxutils import escape as xml_escapedef DirAsXML(path):    result = '<dir>n<name>%s</name>n' % xml_escape(os.path.basename(path))    dirs = []    files = []    for item in os.listdir(path):        itempath = os.path.join(path, item)        if os.path.isdir(itempath): dirs.append(item)        elif os.path.isfile(itempath): files.append(item)    if files:        result += '  <files>n'  + 'n'.join('    <file>n      <name>%s</name>n    </file>' % xml_escape(f) for f in files) + 'n  </files>n'    if dirs:        for d in dirs: x = DirAsXML(os.path.join(path, d)) result += 'n'.join('  ' + line for line in x.split('n'))    result += '</dir>'    return resultif __name__ == '__main__':    print '<structure>n' + DirAsXML(os.getcwd()) + 'n</structure>'

就个人而言,我建议使用一种较为简单的XML模式,将名称放入属性中并摆脱该

<files>
组:

import osfrom xml.sax.saxutils import quoteattr as xml_quoteattrdef DirAsLessXML(path):    result = '<dir name=%s>n' % xml_quoteattr(os.path.basename(path))    for item in os.listdir(path):        itempath = os.path.join(path, item)        if os.path.isdir(itempath): result += 'n'.join('  ' + line for line in      DirAsLessXML(os.path.join(path, item)).split('n'))        elif os.path.isfile(itempath): result += '  <file name=%s />n' % xml_quoteattr(item)    result += '</dir>'    return resultif __name__ == '__main__':    print '<structure>n' + DirAsLessXML(os.getcwd()) + 'n</structure>'

这给出了如下输出:

<structure><dir name="local">  <dir name=".hg">    <file name="00changelog.i" />    <file name="branch" />    <file name="branch.cache" />    <file name="dirstate" />    <file name="hgrc" />    <file name="requires" />    <dir name="store">      <file name="00changelog.i" />

等等

如果

os.walk()
更像
expat
的回调那样工作,那么您会更轻松。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/653311.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号