# -*- coding: utf-8 -*-
# Author :Gogh
# @Time :2017/11/14 22:37
# @Email :[email protected]
# 编写一个search(s)的函数,将当前目录及其所有子目录下
# 查找文件名包含指定字符串的文件,打印完整路径
import os, logging, pdb
def search(s):
rootdir = 'C:/ ' # 指明被遍历的文件夹
#三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
for parent, dirnames, filenames in os.walk(rootdir):
for filename in filenames: # 输出文件信息
# print "filename is:" + filename
if filename.find(s) != -1:
print "the full path of the file is:" + os.path.abspath(os.path.join(parent,filename)) # 输出文件路径信息
if __name__ == '__main__':
search('.log')
# 两种办法实现查找指定目录及子目录下所有包含关键字的文件,并打印出路径
logging.basicConfig(level=logging.DEBUG)
def search_dir(path, L):
current_dir = os.listdir(path)
# pdb.set_trace()
for n in current_dir:
# pdb.set_trace()
new_path = os.path.join(path, n)
if os.path.isfile(new_path): # 需传入路径而非仅仅文件名,否则是FALSE
logging.debug('%s is a file.' % n)
L.append(new_path)
else:
search_dir(new_path, L)
return L
def search(s):
L = search_dir('.', [])
# pdb.set_trace()
for file in L:
# pdb.set_trace()
if file.find(s) != -1:
logging.info('找到包含%s的文件路径:%s' % (s, os.path.abspath(file)))
# os.path.abspath(url) 并非返回url真正完整的绝对路径,只是将当前目录与url进行join操作
# 例如,当前目录为 D:/workplace
# url是 test.txt,实际是在 ./aaa/test.txt
# 但该函数返回的是 D:/workplace/test.txt
if __name__ == '__main__':
search('test')