鱼C论坛

 找回密码
 立即注册
查看: 2497|回复: 2

[已解决]python30课 课后作业第二题

[复制链接]
发表于 2018-9-2 00:13:46 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
python30课 课后作业第二题   用户输入文件名以及开始搜索的路径,搜索该文件是否存在 输出路径 问题在注释


import os

def search_file(start_dir, target) :
    os.chdir(start_dir)
   
    for each_file in os.listdir(os.curdir) :                                                              #这里的os.curdir是指 start_dir目录的么    为什么把os.curdir改成start_dir的话  会报错   不懂
        if each_file == target :
            print(os.getcwd() + os.sep + each_file) # 使用os.sep是程序更标准
        if os.path.isdir(each_file) :
            search_file(each_file, target) # 递归调用
            os.chdir(os.pardir) # 递归调用后切记返回上一层目录

start_dir = input('请输入待查找的初始目录:')      
target = input('请输入需要查找的目标文件:')         
search_file(start_dir, target)                                 #初始目录和目标文件
最佳答案
2018-9-2 00:27:33
import os

def search_file(start_dir, target) :
    os.chdir(start_dir)
   
    for each_file in os.listdir(os.curdir) :                                                              #这里的os.curdir是指 start_dir目录的么    为什么把os.curdir改成start_dir的话  会报错   不懂
        if each_file == target :
            print(os.getcwd() + os.sep + each_file) # 使用os.sep是程序更标准
        if os.path.isdir(each_file) :
            search_file(each_file, target) # 递归调用
            os.chdir(os.pardir) # 递归调用后切记返回上一层目录

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

实参、形参。没被调用到呀,直接从现在的路径去找,不一定 找得到
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-9-2 00:27:33 | 显示全部楼层    本楼为最佳答案   
import os

def search_file(start_dir, target) :
    os.chdir(start_dir)
   
    for each_file in os.listdir(os.curdir) :                                                              #这里的os.curdir是指 start_dir目录的么    为什么把os.curdir改成start_dir的话  会报错   不懂
        if each_file == target :
            print(os.getcwd() + os.sep + each_file) # 使用os.sep是程序更标准
        if os.path.isdir(each_file) :
            search_file(each_file, target) # 递归调用
            os.chdir(os.pardir) # 递归调用后切记返回上一层目录

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

实参、形参。没被调用到呀,直接从现在的路径去找,不一定 找得到
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2018-9-2 13:48:04 | 显示全部楼层
claws0n 发表于 2018-9-2 00:27
import os

def search_file(start_dir, target) :

对对对  谢谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-22 08:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表