|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
编写一段查找文本文件(.txt)的代码,发现递归后会报错,怎么回事?
import os
def search_file(file_name,file_extension):
os.chdir(file_name)
for each_file in os.listdir(os.curdir):
ext=os.path.splitext(each_file)[1]
if ext==file_extension:
print(os.getcwd()+os.sep+each_file)
if os.path.isdir(each_file):
search_file(file_name,file_extension)
os.chdir(os.pardir)
file_name=r'C:\Users\Administrator\Desktop\1'
file_extension='.txt'
search_file(file_name,file_extension)
报错的提示为:
Traceback (most recent call last):
File "F:/pythonProject/test.py", line 15, in <module>
search_file(file_name,file_extension)
File "F:/pythonProject/test.py", line 9, in search_file
search_file(file_name,file_extension)
File "F:/pythonProject/test.py", line 9, in search_file
search_file(file_name,file_extension)
File "F:/pythonProject/test.py", line 9, in search_file
search_file(file_name,file_extension)
[Previous line repeated 992 more times]
File "F:/pythonProject/test.py", line 5, in search_file
ext=os.path.splitext(each_file)[1]
File "D:\Python\Python36\lib\ntpath.py", line 227, in splitext
return genericpath._splitext(p, '\\', '/', '.')
File "D:\Python\Python36\lib\genericpath.py", line 127, in _splitext
sepIndex = max(sepIndex, altsepIndex)
RecursionError: maximum recursion depth exceeded in comparison
告诉我是属于递归超出范围,但是我已经写了os.chdir(os.pardir)返回上一层目录了为什么还会报错?
import os
def search_file(path , file_extension):
try:
for each in os . listdir(path):
x = os . path . join(path , each)
if os . path . isfile(x):
if os . path . splitext(each)[1] . lower() == file_extension . lower():
print(x)
elif os . path . isdir(x):
search_file(x , file_extension)
except Exception as e:
print(e)
path = r'C:\Users\Administrator\Desktop\1'
file_extension='.txt'
search_file(path , file_extension)
|
|