关于对目录和文件的操作
最近在看廖雪峰的python教程,看到了这样一个题目练习:编写一个search(s)的函数,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出完整路径:
$ python search.py test
unit_test.log
py/test.py
py/test_os.py
my/logs/unit-test-result.txt
我的是win10,代码如下:$ python search.py test
unit_test.log
py/test.py
py/test_os.py
my/logs/unit-test-result.txt
程序代码:
#coding=utf-8 import os def search(s, dir = '.'): absPath = os.path.abspath('.') for i in os.listdir(absPath): # dir = os.path.join(absPath,i) # print i,dir.decode('gbk') if os.path.isdir(i): dir2 = os.path.join(absPath, i) search(s, dir2) elif os.path.isfile(i) and s in i: #pass print absPath+i if __name__ == '__main__': search('.py')但是一直提示错误:
.........
File "E:/ѧϰ/Python/test/test.py", line 14, in search
search(s, dir2.decode('gbk'))
File "E:/ѧϰ/Python/test/test.py", line 14, in search
search(s, dir2.decode('gbk'))
File "E:/ѧϰ/Python/test/test.py", line 7, in search
absPath = os.path.abspath('.')
File "C:\Python27\lib\ntpath.py", line 495, in abspath
return normpath(path)
File "C:\Python27\lib\ntpath.py", line 418, in normpath
backslash, dot = (u'\\', u'.') if isinstance(path, _unicode) else ('\\', '.')
RuntimeError: maximum recursion depth exceeded while calling a Python object
一直没搞明白哪里错了File "E:/ѧϰ/Python/test/test.py", line 14, in search
search(s, dir2.decode('gbk'))
File "E:/ѧϰ/Python/test/test.py", line 14, in search
search(s, dir2.decode('gbk'))
File "E:/ѧϰ/Python/test/test.py", line 7, in search
absPath = os.path.abspath('.')
File "C:\Python27\lib\ntpath.py", line 495, in abspath
return normpath(path)
File "C:\Python27\lib\ntpath.py", line 418, in normpath
backslash, dot = (u'\\', u'.') if isinstance(path, _unicode) else ('\\', '.')
RuntimeError: maximum recursion depth exceeded while calling a Python object