
贴一段自己写的代码,主要实现以下功能:
import os def dir_walk(src_path,det_path=None): if os.path.isdir(src_path): if det_path and not os.path.isdir(det_path): os.makedirs(det_path) for name in os.listdir(src_path): _src_path = os.path.join(src_path,name) _det_path = det_path and os.path.join(det_path,name) yield from dir_walk(_src_path,_det_path) if os.path.isfile(src_path): yield src_path,det_path for i,_ in dir_walk('/home'): print(i) 主要有几个疑问,大家帮忙试着解答下哈:
1 AILOVEU OP 这个帖子上去啊 |
2 neoblackcap 2019-05-07 11:29:34 +08:00 os.walk 有什么满足不了吗? |
3 momo1999 2019-05-07 12:02:23 +08:00 过早优化是万恶之源。能用就行 |
4 Ct5T66PVR1bW7b2z 2019-05-07 12:09:53 +08:00 via Android 递归就是坑坑坑坑 |
5 AILOVEU OP @neoblackcap 不能复制到新的文件夹下,它只能遍历 |
6 liukrystal 2019-05-07 12:43:49 +08:00 为什么不用 os.walk()而是自己造轮子... |
7 jeadong 2019-05-07 12:52:27 +08:00 知道 dir 命令 |
8 atx 2019-05-07 13:20:14 +08:00 python3.5 及以上用 os.scandir 会更快一点 |
9 AILOVEU OP @liukrystal 不光是遍历,主要是第二个参数,可以用于复制文件等 |
12 casparchen 2019-05-07 13:39:37 +08:00 via iPad 没看懂其中有什么是 os.walk 不能做,而这段代码能做的 |
14 AILOVEU OP 如果不用 yield,递归是很容易实现的,因为最近学到了,所以就想把它包装成一个方法; os.walk 也可以勉强完成处理后复制文件的功能,但用起来会很别扭 |
15 AILOVEU OP @lc1450 Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information |
16 atx 2019-05-07 13:57:49 +08:00 @AILOVEU 不好意看错了 os.walk 文档下面解释 Changed in version 3.5: This function now calls os.scandir() instead of os.listdir(), making it faster by reducing the number of calls to os.stat(). scandir 和 walk 一般都直接用来迭代目录,还以为这俩是一样的 |
17 AILOVEU OP |