簡體   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