繁体   English   中英

目录列表到xml-无法连接'str'和'NoneType'对象-如何处理?

[英]directory listing to xml - cannot concatenate 'str' and 'NoneType' objects - How To Handle?

在这里我发现使用一部分脚本在Windows PC上的目录中运行以生成XML文件。 但是,我遇到了以上错误,并且不确定如何处理该错误。 我添加了一个try / except,但是它仍然崩溃了。 如果我将目录“ DirTree3(“ C:/”)”替换为“ DirTree3((os.getcwd())”,将目录设置为当前工作目录,则此方法非常有效

def DirTree3(path):
    try:
        result = '<dir>%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
                                    DirTree3(os.path.join(path, item)).split('\n'))
            elif os.path.isfile(itempath):
                result += '  <file> %s </file>\n' % xml_quoteattr(item)
        result += '</dir> \n'
        return result
    except Exception:
        pass


print '<DirectoryListing>\n' + DirTree3("C:/") + '\n</DirectoryListing>'

附带说明,此脚本将在没有管理员特权的系统上运行,因此不能以admin身份运行

根据您在下面有关获取和希望忽略任何路径访问错误的评论,我在下面的答案中修改了代码,以尽其所能。 请注意,如果发生其他类型的异常,它将仍然终止。

def DirTree3(path):
    try:
        result = '<dir>%s\n' % xml_quoteattr(os.path.basename(path))
        try:
            items = os.listdir(path)
        except WindowsError as exc:
            return '<error> {} </error>'.format(xml_quoteattr(str(exc)))

        for item in items:
            itempath = os.path.join(path, item)
            if os.path.isdir(itempath):
                result += '\n'.join('  ' + line for line in
                                    DirTree3(os.path.join(path, item)).split('\n'))
            elif os.path.isfile(itempath):
                result += '  <file> %s </file>\n' % xml_quoteattr(item)
        result += '</dir> \n'
        return result
    except Exception as exc:
        print('exception occurred: {}'.format(exc))
        raise

print '<DirectoryListing>\n' + DirTree3("C:/") + '\n</DirectoryListing>'

暂无
暂无

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

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