glob : 파일명을 리스트 형식으로 반환하는 함수
와일드 카드(*, ?)를 통해 조건을 명시할 수 있다
# dir : file1.txt, file2.txt, filea.txt, fileb.txt, file1.jpg
# dir/subdir : subfile1.txt, subfile2.txt
import glob
# '*'는 모든 문자열을 의미한다.
glob.glob(./*)
glob.glob(*)
>> (현재 폴더의 하위 폴더와 파일)
output = glob.glob('dir/*.txt')
print(output)
>>['dir/file1.txt', 'dir/file101.txt', 'dir/file102.txt', 'dir/file2.txt', 'dir/filea.txt', 'dir/fileb.txt']
# '?'는 한자리의 문자를 의미한다.
output = glob.glob('dir/file?.*')
print(output)
>>['dir/file1.bmp', 'dir/file1.txt', 'dir/file2.bmp', 'dir/file2.txt', 'dir/filea.txt', 'dir/fileb.txt']
✔ 하위 폴더 접근
재귀형 사용 또는 **로 폴더의 하위 파일들까지 반환시킬 수 있다.
glob.glob('**/*',recursive=True)
glob.glob('./dir/**',recursive=True)
✔ 파일명에 특정 값이 들어가는 파일 호출
glob.glob('./[0-9].*')
['./1.gif', './2.txt']
glob.glob('*.gif')
['1.gif', 'card.gif']
glob.glob('?.gif')
['1.gif']
glob.glob('**/*.txt', recursive=True)
['2.txt', 'sub/3.txt']