[英]directory listing to xml - cannot concatenate 'str' and 'NoneType' objects - How To Handle?
Using part of a script I found on here to run through the directories on a Windows PC to produce an XML file. 在这里我发现使用一部分脚本在Windows PC上的目录中运行以生成XML文件。 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. 我添加了一个try / except,但是它仍然崩溃了。 This works perfectly if i set the directory to be my Current Working Directory by replacing the "DirTree3("C:/") " with "DirTree3((os.getcwd())" 如果我将目录“ 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>'
As a side note, this script will be run on a system without admin privileges so running as admin is not an option 附带说明,此脚本将在没有管理员特权的系统上运行,因此不能以admin身份运行
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>'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.