Discuss / Python / 第二题

第二题

Topic source

jhbbbbbbbbbbb

#1 Created at ... [Delete] [Delete and Lock User]
import os

def find_file(file,PATH='.'):
    for maindir,subdirs,files in os.walk(PATH):
        for filename in files:
            if file in filename:
                print(os.path.join(maindir,filename))


find_file('FILENAME','SEARCH_PATH') #    A test

jhbbbbbbbbbbb

#2 Created at ... [Delete] [Delete and Lock User]

另一种实现:

import os

def find(file,PATH='.'):
    for x in os.listdir(PATH):
        if os.path.isfile(x) and (file in x):
            print('found!',os.path.join(PATH,x))
        if os.path.isdir(x):
            find(file,os.path.join(PATH,x))

为什么这个方法搜不到某些子目录下的文件?

大鱼__巛

#3 Created at ... [Delete] [Delete and Lock User]

在for下面加上一条语句变成绝对路径就行了

x = os.path.join(PATH, x)

我是iboy啊

#4 Created at ... [Delete] [Delete and Lock User]

我也想知道为什么

我是iboy啊

#5 Created at ... [Delete] [Delete and Lock User]

def Search(str, path='.'): for x in os.listdir(path): if os.path.isfile(os.path.join(path, x)) and (str in x): print('found!',os.path.join(path,x)) if os.path.isdir(x): Search(str,os.path.join(path,x)) 你看一下!

jhbbbbbbbbbbb

#6 Created at ... [Delete] [Delete and Lock User]

@我是iboy啊 试试倒数第二行改为if os.path.isdir(os.path.join(PATH,x):

jhbbbbbbbbbbb

#7 Created at ... [Delete] [Delete and Lock User]

上面少个右括号)。。。

chirlyai

#8 Created at ... [Delete] [Delete and Lock User]

不能搜子目录在于isdir和isfile函数的参数,假如只写文件名,他很可能是不能识别的,因此,在判断的时候要将路径写进去isfile(os.path.join(path,file)) 我这里只写了相对路径,运行成功,不知道是不是有些地方一定需要绝对路径


  • 1

Reply