练习:编写一个search(s)
的函数,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出完整路径:
$ python search.py test
unit_test.log
py/test.py
py/test_os.py
my/logs/unit-test-result.txt
code:
# -*- coding: utf-8 -*- 'Search a file with its filename'
__author__='spook' import os num = 0 def search(dirPath,fileName): global num for y in os.listdir(dirPath): absPath = os.path.join(dirPath,y).decode('gbk').encode('utf-8') if os.path.isdir(absPath): try: search(absPath,fileName) except BaseException, e: continue elif (os.path.isfile(absPath) and os.path.split(absPath)[1]==fileName): num +=1 print('found %s '%absPath.decode('gbk').encode('utf-8'))
#search('D:\CreateFromPDM','README.txt') search('D:\','README.txt') print("%d founded"%num)
附:split与join
os.path.split() 按照路径将文件名和路径分割开,比如d:\python\python.ext,可分割为['d:\python', 'python.exe']
import os print os.path.split('c:\Program File\123.doc') print os.path.split('c:\Program File\') -----------------output--------------------- ('c:\Program File', '123.doc') ('c:\Program File', '')
os.path.join(path1[,path2[,......]]) split的逆过程
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略。 >>> os.path.join('c:\', 'csv', 'test.csv') 'c:\csv\test.csv' >>> os.path.join('windows emp', 'c:\', 'csv', 'test.csv') 'c:\csv\test.csv' >>> os.path.join('/home/aa','/home/aa/bb','/home/aa/bb/c') '/home/aa/bb/c'