在这里我发现使用一部分脚本在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>'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句