鱼C论坛

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

简单的递归问题

[复制链接]
发表于 2019-5-1 12:51:46 | 显示全部楼层 |阅读模式

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

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

x
一个查找给定路径下的视频格式的程序,死循环了,大神指教一下问题出在了哪里!

  1. import os

  2. def func(open_file):
  3.     first_file=os.getcwd()

  4.     os.chdir(open_file)
  5.    
  6.     ext_set=set()
  7.    
  8.     for each_file in os.listdir():
  9.         if  os.path.isdir(each_file):
  10.             func(each_file)
  11.             os.chdir(os.pardir)

  12.         else:
  13.             ext=os.path.splitext(each_file)
  14.             if ext[1] in ('avi','.rmvb','.mp4'):
  15.                 video_list.append(os.getcwd()+each_file)
  16.                 print(video_list)
  17.                
  18.                


  19. open_file=input('请输入要查找的文件目录:')
  20. video_list=[]
  21. func(open_file)
  22. txt=open_file+'videolist.txt'
  23. txt=open(txt,'w')
  24. txt.writelines(video_list)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-5-1 13:35:22 | 显示全部楼层
    这一行有问题:
  1.     for each_file in os.listdir():
复制代码

    应该改成这样:
  1.     for each_file in os.listdir(os.getcwd()):
复制代码

    我把楼主的代码优化了一下,可以自动跨过没有访问权限的目录,使用不受限制,楼主可以测试一下。
  1. import os

  2. def func(open_file , type_list):
  3.     try:
  4.         for each_file in os . listdir(open_file):
  5.             x = os . path . join(open_file , each_file)
  6.             if os . path . isfile(x) :
  7.                 ext = os . path . splitext(each_file)[1] . lower()
  8.                 if ext in type_list :
  9.                     video_list . append(x)
  10.             elif os . path . isdir(x) :
  11.                 func(x , type_list)
  12.     except:
  13.         pass

  14. open_file = input('请输入要查找的文件目录:')
  15. video_list = []
  16. func(open_file , ('.avi' , '.rmvb' , '.mp4' , '.mkv' , '.flv' , '.wmv'))
  17. txt = os . path . join(open_file , 'videolist.txt')
  18. with open(txt , 'w') as f:
  19.     for x in video_list :
  20.         print(x)
  21.         f . write(x + '\n')
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2019-5-1 14:28:38 | 显示全部楼层
jackz007 发表于 2019-5-1 13:35
这一行有问题:

    应该改成这样:

哈哈哈  你这个还有许多语句我还没学  看不懂     但是我那个在你给出改正后还是循环个没完
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-1-15 15:25

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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