1. 編寫一個程序,能在當前目錄以及當前目錄的所有子目錄下查找文件名包含指定字符串的文件,並打印出絕對路徑。
https://blog.csdn.net/lilong117194/article/details/74537595
import os
class SearchFile(object):
def __init__(self,path='.'):
self._path=path
self.abspath=os.path.abspath(self._path) # 默認當前目錄
def findfile(self,keyword,root):
filelist=[]
for root,dirs,files in os.walk(root):
for name in files:
fitfile=filelist.append(os.path.join(root, name))
#print(fitfile)
print(os.path.join(root, name))
#print(filelist)
print('...........................................')
for i in filelist:
if os.path.isfile(i):
#print(i)
if keyword in os.path.split(i)[1]:
print('yes!',i) # 絕對路徑
#else:
#print('......no keyword!')
def __call__(self):
while True:
workpath=input('Do you want to work under the current folder? Y/N:')
if(workpath == ''):
break
if workpath=='y' or workpath=='Y':
root=self.abspath # 把當前工作目錄作爲工作目錄
print('當前工作目錄:',root)
dirlist=os.listdir() # 列出工作目錄下的文件和目錄
print(dirlist)
else:
root=input('please enter the working directory:')
print('當前工作目錄:',root)
keyword=input('the keyword you want to find:')
if(keyword==''):
break
self.findfile(keyword,root) # 查找帶指定字符的文件
if __name__ == '__main__':
search = SearchFile()
search()
2.下面用一個遍歷文件夾下的文件來說明上述函數的應用,在實際項目中,當然可以用os.walk()或者os.path.walk()來完成這個工作(程序設計的核心是設計的創意,而不是所處的宏觀層次)。
https://blog.csdn.net/fengda2870/article/details/48787129
import os
Const_Image_Format = [".jpg",".jpeg",".bmp",".png"]
class FileFilt:
fileList = [""]
counter = 0
def __init__(self):
pass
def FindFile(self,dirr,filtrate = 1):
global Const_Image_Format
for s in os.listdir(dirr):
newDir = os.path.join(dirr,s)
if os.path.isfile(newDir):
if filtrate:
if newDir and(os.path.splitext(newDir)[1] in Const_Image_Format):
self.fileList.append(newDir)
self.counter+=1
else:
self.fileList.append(newDir)
self.counter+=1
if __name__ == "__main__":
b = FileFilt()
b.FindFile(dirr = "D:\Python27\user\dapei-imgs")
print(b.counter)
for k in b.fileList:
print k