Python glob 사용법 - Python glob sayongbeob

컴공돌이의 스터디 블로그

glob의 glob()를 사용해서 모든 파일에 작업하기


파이썬 버전 : Python 3.6.2

사용 에디터 : PyCharm

 데이터셋이 온전한 하나이면 문제가 되지 않겠지만 일반적인 경우 외부에서 수집한 데이터는 여러개의 파일에 나눠서 저장이 되어 있는 경우가 많습니다. 이런 경우 파일을 1개씩 접근해서 작업을 해야 합니다. 

import glob

import pandas as pd

path = "파일들이 들어있는 폴더의 경로"

file_list = glob.glob(path + "\\*.csv")

for file in file_list:

current_data = pd.read_csv(file, encoding="cp949")

print(current_data)

cs

  위의 코드를 실행하면 간단하게 경로 내부에 존재하는 여러개의 파일에 대해서 동일한 작업을 수행할 수 있습니다.

개발자D

주제 : os 또는 glob를 활용한 파일리스트 가져오기

모든 데이터가 하나의 파일로 되어있다면 편하겠지만, 일반적으로 그렇지 않습니다.
그래서 해당 특정파일 이름을 리스트로 가져오는 작업을 진행하고자 합니다.

Python glob 사용법 - Python glob sayongbeob
C:/Users/BIGDATA/Subir2/Data/노원구(이하 "파일위치"로 명함)

# import os

os를 활용하여 해당파일위치에서 .csv로 끝나는 모든 파일명을 가져올수 있습니다

import os

DIR_IN = "데이터위치 절대경로"

file_list = os.listdir(DIR_IN)
for file in file_list:          # 코드간결화 작업전
    if file.endswith(".csv"):
        print(file)

또는 아래와 같이 코드를 간결화하여 사용 가능합니다

import os

DIR_IN = "데이터위치 절대경로"

file_list = os.listdir(DIR_IN)
file_list_csv = [file for file in file_list if file.endswith(".csv")] # 코드간결화 작업후
Python glob 사용법 - Python glob sayongbeob
os.listdir 결과

# import glob

glob를 활용하여 동일하게 데이터위치에서 .csv로 끝나는 모든 파일명을 가져올수 있습니다

import glob

input_path = "데이터위치 절대경로/*.csv"  
for f in glob.glob(input_path):          # 코드간결화 작업전
	print(f)

또는 아래와 같이 코드를 간결화하여 사용 가능합니다

import glob

input_path = "데이터위치 절대경로/*.csv"
file_list = [f for f in glob.glob(input_path)] # 코드간결화 작업후
Python glob 사용법 - Python glob sayongbeob
glob.glob 결과

# 차이점

결과값을 보면, 확연한 차이를 볼 수 있습니다

Python glob 사용법 - Python glob sayongbeob
(좌) os.listdir (우) glob.glob

os.listdir의 경우, 해당 디렉토리의 파일명만 가져오지만,
glob으로 파일 리스트를 가져올 경우 경로명을 포함합니다. 


### Reference

  • 꾸르잼's 코드블로그(이전 블로그) blog.naver.com/woosoung1993/221641851084

소스 코드: Lib/glob.py


The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. This is done by using the os.scandir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell.

Note that files beginning with a dot (.) can only be matched by patterns that also start with a dot, unlike fnmatch.fnmatch() or pathlib.Path.glob(). (For tilde and shell variable expansion, use os.path.expanduser() and os.path.expandvars().)

리터럴 일치를 위해서는, 대괄호 안에 메타 문자를 넣습니다. 예를 들어, '[?]''?' 문자와 일치합니다.

더 보기

pathlib 모듈은 고수준의 경로 객체를 제공합니다.

glob.glob(pathname, *, root_dir=None, dir_fd=None, recursive=False)

Return a possibly empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file be included is unspecified.

If root_dir is not None, it should be a path-like object specifying the root directory for searching. It has the same effect on glob() as changing the current directory before calling it. If pathname is relative, the result will contain paths relative to root_dir.

This function can support paths relative to directory descriptors with the dir_fd parameter.

recursive가 참이면, “**” 패턴은 모든 파일과 0개 이상의 디렉터리, 서브 디렉터리 및 디렉터리로의 심볼릭 링크와 일치합니다. 패턴 다음에 os.sep이나 os.altsep이 오면, 파일은 일치하지 않습니다.

pathname, recursive를 인자로 감사 이벤트(auditing event) glob.glob을 발생시킵니다.

Raises an auditing event glob.glob/2 with arguments pathname, recursive, root_dir, dir_fd.

참고

커다란 디렉터리 트리에서 “**” 패턴을 사용하면 과도한 시간이 걸릴 수 있습니다.

버전 3.5에서 변경: **” 를 사용하는 재귀적 glob 지원.

버전 3.10에서 변경: Added the root_dir and dir_fd parameters.

glob.iglob(pathname, *, root_dir=None, dir_fd=None, recursive=False)

실제로 동시에 저장하지 않고 glob()과 같은 값을 산출하는 이터레이터를 반환합니다.

pathname, recursive를 인자로 감사 이벤트(auditing event) glob.glob을 발생시킵니다.

Raises an auditing event glob.glob/2 with arguments pathname, recursive, root_dir, dir_fd.

버전 3.5에서 변경: **” 를 사용하는 재귀적 glob 지원.

버전 3.10에서 변경: Added the root_dir and dir_fd parameters.

glob.escape(pathname)

모든 특수 문자('?', '*''[')를 이스케이프 처리합니다. 이것은 특수 문자가 들어있을 수 있는 임의의 리터럴 문자열을 일치시키려는 경우에 유용합니다. 드라이브/UNC 셰어 포인트의 특수 문자는 이스케이프 되지 않습니다, 예를 들어, 윈도우에서 escape('//?/c:/Quo vadis?.txt')'//?/c:/Quo vadis[?].txt'를 반환합니다.

버전 3.4에 추가.

예를 들어, 다음과 같은 파일을 포함하는 디렉터리를 고려하십시오: 1.gif, 2.txt, card.gif3.txt 파일 만 포함하는 서브 디렉터리 sub. glob()은 다음과 같은 결과를 산출합니다. 경로의 선행 구성 요소가 보존되는 방법에 유의하십시오.

>>> import glob
>>> 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']
>>> glob.glob('./**/', recursive=True)
['./', './sub/']

디렉터리에 .으로 시작하는 파일이 있으면, 기본적으로 일치하지 않습니다. 예를 들어, card.gif.card.gif를 포함하는 디렉터리를 고려하십시오:

>>> import glob
>>> glob.glob('*.gif')
['card.gif']
>>> glob.glob('.c*')
['.card.gif']

더 보기

모듈 fnmatch

셸 스타일 파일명 (경로가 아님) 확장