python面试题21-40

python编程题21-40

21.编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出绝对路径。

答案:

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(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()
Do you want to work under the current folder? Y/N:y
当前工作目录: E:\mhh-jupyter\python面试题-mhh
['.ipynb_checkpoints', '1.python基础1-20.ipynb', '1.python基础21-40.ipynb', 'A文档说明.md', 'newFile.txt', 'temp', 'web后台框架.md', '前端.md', '基础.md', '数据分析.md', '数据库.md', '爬虫.md']
the keyword you want to find:数据
E:\mhh-jupyter\python面试题-mhh\1.python基础1-20.ipynb
E:\mhh-jupyter\python面试题-mhh\1.python基础21-40.ipynb
E:\mhh-jupyter\python面试题-mhh\A文档说明.md
E:\mhh-jupyter\python面试题-mhh\newFile.txt
E:\mhh-jupyter\python面试题-mhh\web后台框架.md
E:\mhh-jupyter\python面试题-mhh\前端.md
E:\mhh-jupyter\python面试题-mhh\基础.md
E:\mhh-jupyter\python面试题-mhh\数据分析.md
E:\mhh-jupyter\python面试题-mhh\数据库.md
E:\mhh-jupyter\python面试题-mhh\爬虫.md
E:\mhh-jupyter\python面试题-mhh\.ipynb_checkpoints\1.python基础1-20-checkpoint.ipynb
E:\mhh-jupyter\python面试题-mhh\.ipynb_checkpoints\1.python基础21-40-checkpoint.ipynb
E:\mhh-jupyter\python面试题-mhh\t
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值