2011-08-10 30 views
-1

這段代碼有什麼問題?我想在文件夾中找到指定的文件。 Thansk爲你提供幫助。Python,找到文件夾中的指定文件

import os, fnmatch 

def find(root, mask): //Error 
    files_list = os.listdir(os.path.abspath(root)) 
    for filename in fnmatch.filter(files_list, mask): 
     yield filename 

def test(): 
    res = find ('D:\\Sample\\', 'hallo.txt') 

test() 

錯誤:

Error: Traceback (most recent call last): def find(root, mask): NoneType 
+1

'os.dir'應該是什麼? –

+0

那麼你有什麼錯誤,或者你的代碼有什麼問題? – sth

+0

@sth:對不起,我沒有寫錯誤代碼:-) – abcdef

回答

1

你的函數是generator,它會產生一個文件名由一個。您可以撥打reslist如果你希望所有匹配的列表:

list_of_matches = list(res) 

同樣的root=os.dir默認的說法是沒有意義的。也許用'.'

+1

如果他只想要第一個,也可能只匹配,使用'match = next(find('D:\\ Sample \\','hallo.txt'))''。 – agf

0

一些縮進失蹤測試功能

def test(): 
    res = find ('D:\\Sample\\', 'hallo.txt') 
+0

這幾乎肯定只是一個複製粘貼縮進錯誤。 – agf

相關問題