2010-03-14 3 views

답변

0

비 재귀 :

for x in os.listdir(dir): 
    if x.endswith(fext): 
     filename = os.path.join(dir, x) 
     # do your stuff here 
+0

'os.path.join'이 필요합니까? 나는'x' 자체가'filename'이라고 생각합니다. –

+0

x는 적어도 python 2.5와 python 2.6에서는 디렉토리 이름이없는 파일명 일뿐입니다. IIRC –

+0

이것은 버그가있어서'.py' 파일을 찾을 때'.epy' 파일을 잡습니다. 또한, glob.glob는이 작업에 적합한 도구입니다. –

4

저는 다음과 비슷한 것을하고 싶습니다 : /dir/to/search/*.extension?

import glob 
files = glob.glob('/path/*.extension') 

편집 :

이 여기 글로브라고하고 그것을 사용하는 방법이며, 여기 문서입니다 : http://docs.python.org/library/glob.html

+0

참으로 내가 원하는 것은이 창에서 작동합니까? –

+0

이것이 작동하지 않을 이유가 없습니다. "이것은 서브 쉘을 실제로 호출하는 것이 아니라 os.listdir() 및 fnmatch.fnmatch() 함수를 사용하여 수행됩니다." (나는 이것이 당신의 문제에 대한 올바른 해결책이라고 믿는다. 자신을 만들기 전에 내장 기능을 선호해야한다.) – adamse

1
import os 
root="/home" 
ext = raw_input("Put file extension to search: ") 
path = raw_input("Dir to search in: ") 
for r,d,f in os.walk(path): 
    for files in f: 
     if files.endswith(ext): 
       print "found: ",os.path.join(r,files) 
-1

다음과 같이 간단하게 작성할 수 있습니다.

import os 
ext = raw_input("Put file extension to search: ") 
path = raw_input("Dir to search in: ") 
matching_files = [os.path.join(path, x) for x in os.listdir(path) if x.endswith(ext)] 
+0

호기심에서 벗어난 이유 -이 솔루션은 왜 투표를 중단 했습니까? – mojbro

관련 문제