2011. 11. 20. 23:07

glob 모듈은 윈도우의 dir 명령어나 리눅스의 ls 명령어와 유사한 기능을 제공합니다.

 

glob.glob(path)

 

glob() 함수는 경로에 대응되는 모든 파일 및 디렉터리의 리스트를 반환합니다.

'*''?'도 사용가능하며 "[""]"를 사용한 문자열 비교도 가능합니다.

>>> glob.glob('*')

['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'pythonw.exe', 'README.txt', 'tcl', 'Tools', 'w9xpopen.exe']

>>> glob.glob('./[0-9].*')

['./1.gif', './2.txt']

>>> glob.glob('*.gif')

['1.gif', 'card.gif']

>>> glob.glob('?.gif')

['1.gif']

>>> glob.glob('*.exe')

['python.exe', 'pythonw.exe', 'w9xpopen.exe']

>>> from os.path import *

>>> glob.glob(abspath('.' + '\\*.exe'))

['C:\\Python30\\python.exe', 'C:\\Python30\\pythonw.exe', 'C:\\Python30\\w9xpopen.exe']

 

glob.iglob(path)

 

glob과 동일한 동작을 수행하지만, 리스트로 결과를 반환하는 것이 아니라 이터레이터를 반환.

한번에 모든 결과를 리스트에 담지 않으므로, 결과가 매우 많은 경우 유용하게 쓰일 수 있다.

>>> glob.iglob('*')

<generator object iglob at 0x012230D0>

>>> for i in glob.iglob('*'):

    print (i)

 

    

DLLs

Doc

include

Lib

libs

LICENSE.txt

NEWS.txt

python.exe

pythonw.exe

README.txt

tcl

Tools

w9xpopen.exe

 

 

[ Example ] - Tree 예제

w tree는 하위 디렉터리 구조를 보여 주는 툴입니다.

os.pathglob의 일부 기능을 이용해서 tree와 비슷한 기능을 수행하는 예제 작성.

 

[ tree.py 소스코드 ]

 

[ 실행결과 ]

 

Posted by devanix