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())"
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>'
As a side note, this script will be run on a system without admin privileges so running as admin is not an option
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.
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>'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.