directory listing to xml - cannot concatenate 'str' and 'NoneType' objects - How To Handle?
<p>Using part of a script I found on here to run through the directories on a Windows PC to produce an XML file. However I am running into the above error and I am not sure how to handle the error. I have added a try/except in however it still crashes out. This works perfectly if i set the directory to be my Current Working Directory by replacing the "DirTree3("C:/") " with "DirTree3((os.getcwd())" </p>

<pre><code>def DirTree3(path):
    try:
        result = '&lt;dir&gt;%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 += '  &lt;file&gt; %s &lt;/file&gt;\n' % xml_quoteattr(item)
        result += '&lt;/dir&gt; \n'
        return result
    except Exception:
        pass


print '&lt;DirectoryListing&gt;\n' + DirTree3("C:/") + '\n&lt;/DirectoryListing&gt;'
</code></pre>

<p>As a side note, this script will be run on a system without admin privileges so running as admin is not an option</p>

<p>Based on your comments below about getting and wanting to ignore any path access errors, I modified the code in my answer below to do that as best it can. Note that it will still terminate if some other type of exception occurs.</p>

<pre><code>def DirTree3(path):
    try:
        result = '&lt;dir&gt;%s\n' % xml_quoteattr(os.path.basename(path))
        try:
            items = os.listdir(path)
        except WindowsError as exc:
            return '&lt;error&gt; {} &lt;/error&gt;'.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 += '  &lt;file&gt; %s &lt;/file&gt;\n' % xml_quoteattr(item)
        result += '&lt;/dir&gt; \n'
        return result
    except Exception as exc:
        print('exception occurred: {}'.format(exc))
        raise

print '&lt;DirectoryListing&gt;\n' + DirTree3("C:/") + '\n&lt;/DirectoryListing&gt;'
</code></pre>

python xml