test = r'N:\HBAD '
print(os.listdir(test))
try:
for a in os.listdir(test):
if not os.path.exists(os.path.join(test,get_num(a))):
os.mkdir(os.path.join(test,get_num(a))) #问题是 get_num()一遇到不符合正则的文件就会写入 txt ,然后中断递归
except Exception as e:
print(str(e))
其中不符合正则是,会写入文件,但是:
else:
with open('C:/python/Not_finish.txt','a') as f:
f.write(self + '\n')
f.close()
print(self + ' Not Format')
此代码块没有返回值,所以导致下面一句抛出异常:
os.mkdir(os.path.join(test,get_num(a)))
# 因为get_num执行到最后没匹配,并没有返回值,则默认会返回None
# 所以变成执行-> os.mkdir(os.path.join(test,None))
# 抛出异常
"""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/posixpath.py", line 75, in join
if b.startswith('/'):
AttributeError: 'NoneType' object has no attribute 'startswith'
"""
问题出在这个代码块:
其中不符合正则是,会写入文件,但是:
此代码块没有返回值,所以导致下面一句抛出异常:
然后被外围的try,except捕捉到,于是退出for循环。
另外因为你是初学者,给你提几点建议:
for循环是遍历不是递归
get_num函数,每次不匹配都要重新打开文件,并添加,效率低下,可以传入文件描述符f到此函数中处理即可
with open()语句,最后的f.close是多余的,因为with上下文已经帮你做好了这一切