鱼C论坛

 找回密码
 立即注册
查看: 2563|回复: 3

[已解决]python30讲,课后作业问题

[复制链接]
发表于 2020-11-12 21:07:48 From FishC Mobile | 显示全部楼层 |阅读模式
50鱼币
如果正常输入存在的文件可以找到,但是好像无法进入文件夹进一步搜索,初始目录为根目录的话还会报错
最佳答案
2020-11-12 21:07:49
本帖最后由 jackz007 于 2020-11-12 22:07 编辑
  1. #-*-coding:gbk-*-

  2. import os

  3. def search_file(start_dir , target) :
  4.     try:
  5.         for each_file in os . listdir(start_dir) :
  6.             x = os . path . join(start_dir , each_file)
  7.             if os . path . isfile(x) :
  8.                 if each_file . upper() == target . upper():
  9.                     print(x)
  10.             elif os . path . isdir(x) :
  11.                 search_file(x , target)
  12.     except:
  13.         print('无法查找目录:"%s"' % start_dir)

  14. start_dir = input('请输入待查找的初始目录:') . strip()
  15. if start_dir :
  16.     target = input('请输入需要查找的目标文件:') . strip()
  17.     if target :
  18.         search_file(start_dir, target)
复制代码
Screenshot_2020-11-12-20-03-49-310_com.android.browser.jpg
1605186166050..jpg
1605186433529..jpg
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-11-12 21:07:49 | 显示全部楼层    本楼为最佳答案   
本帖最后由 jackz007 于 2020-11-12 22:07 编辑
  1. #-*-coding:gbk-*-

  2. import os

  3. def search_file(start_dir , target) :
  4.     try:
  5.         for each_file in os . listdir(start_dir) :
  6.             x = os . path . join(start_dir , each_file)
  7.             if os . path . isfile(x) :
  8.                 if each_file . upper() == target . upper():
  9.                     print(x)
  10.             elif os . path . isdir(x) :
  11.                 search_file(x , target)
  12.     except:
  13.         print('无法查找目录:"%s"' % start_dir)

  14. start_dir = input('请输入待查找的初始目录:') . strip()
  15. if start_dir :
  16.     target = input('请输入需要查找的目标文件:') . strip()
  17.     if target :
  18.         search_file(start_dir, target)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2020-11-12 21:37:08 | 显示全部楼层


你新建个文件夹,把你需要测试的文件弄到新的文件夹里去,然后在尝试运行代码

别直接对一整个盘进行查找,否则一般会有隐藏被保护文件无法查找导致报错的

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-11-12 23:39:49 From FishC Mobile | 显示全部楼层
我犯了个严重的错误,"新建文本文档,命名为1.txt",然后搜索1.txt死活搜索不到,其实应该搜索1.txt.txt
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-6-29 13:37

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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