炼己者 发表于 2017-11-2 09:35:29

零基础入门学习python第30讲课后习题

第2题
import os

def search_file(start_dir, target) :
    os.chdir(start_dir)#改变工作目录
   
    for each_file in os.listdir(os.curdir) :   #把当前目录下的文件名附给each_file
      if each_file == target :
            print(os.getcwd() + os.sep + each_file)   # 使用os.sep是程序更标准
      if os.path.isdir(each_file) :      #判断each_file是否存在且是一个目录 if语句后面是真,所以假设存在
            search_file(each_file, target)   # 递归调用
            os.chdir(os.pardir)      # 递归调用后切记返回上一层目录
      #这段if语句目的是为了解决这种情况:如遇到文件夹,则进入文件夹继续搜索
            #我把这段if语句删掉,发现程序依旧可以运行,所以验证了上面的判断,可以运行的原因自然是没有遇到那种问题

start_dir = input('请输入待查找的初始目录:')
target = input('请输入需要查找的目标文件:')
search_file(start_dir, target)

#os.getcwd() 返回当前工作目录os.sep 输出操作系统特定的路径分隔符each_file 当前目录下的文件
页: [1]
查看完整版本: 零基础入门学习python第30讲课后习题