Discuss / Python / 第二题实在是迷茫了,求指教

第二题实在是迷茫了,求指教

Topic source

import os def findfile(x): for root,dirs,files in os.walk('.'): if x in files: print(os.path.join(root,x))

输入findfile('1024')之后,不出结果也不报错,到底是什么原因啊?求大佬指教

import os def findfile(x): for root,dirs,files in os.walk('.'): for file in files:#主要是你少了这一行,其他位置微调下就好 if x in file: print(os.path.join(root,file))

也就是说我忘了让程序在第一个遍历的files中查找文件,导致程序虽然可以运行,但是不知道输出什么了是吗?

http://liangwenxiao.iteye.com/blog/720135 os.walk()的源码, 第13行dirs, nondirs = [], [] 第21行yield top, dirs, nondirs 即os.walk()返回的nondirs也就是你写的files是一个列表,如果直接 for root,dirs,files in os.walk('.'): if x in files: 判断条件就成了x是否在列表中,即搜索的逻辑是目录下是否有名称为x的文件,你可以新建个文件重命名为1024并把扩展名去了,这样按你原来写的就可以搜索出来了 for root,dirs,files in os.walk('.'): for file in files: if x in file: 这样才是判断列表中的 元素的 名称是否包含x.


  • 1

Reply