표준 라이브러리

2025. 1. 6.·언어/Python

파이썬 표준 라이브러리(Standard Library)

파이썬 설치 시 기본적으로 제공되는 모듈과 패키지들의 집합

표준 라이브러리 모듈을 사용하려면, import 문을 이용해 모듈을 가져옴

---------------🐢

datetime

날짜와 시간을 다루는 기능을 제공하는 모듈

date, time, datetime, timedelta, timezone 등의 클래스를 통해 날짜/시간 조작이 가능

datetime.date

연, 월, 일로 날짜 표현

import datetime
day = datetime.date(2025, 1, 6)
day.weekday() # 0 출력 weekday(): 0(월요일)~6(일요일) 
day.isoweekday() # 1 출력 isoweekday(): 1(월요일)~7(일요일)

datetime.time

특정 날짜와 관계없이, 하루가 정확히 24*60*60초를 갖는다는 가정하에 이상적인 시간

datetime.datetime

날짜와 시간의 조합

import datetime
now = datetime.datetime.now()  # 현재 로컬 날짜와 시간

--------------🐢-

time

주로 유닉스 시간(Epoch time)과 일반적인 시간 처리 함수들을 제공하는 모듈

time.time()

1970-01-01 00:00:00 UTC부터 경과한 시간을 초 단위로 부동소수점 값으로 반환

import time
print(time.time()) # 1736142638.8882756

time.localtime()

time.time()이 리턴한 실숫값을 연, 월, 일, 시, 분, 초, ~ 의 구조체로 반환

import time
print(time.localtime(time.time()))
# time.struct_time(tm_year=2025, tm_mon=1, tm_mday=6, tm_hour=14, tm_min=54, tm_sec=24, tm_wday=0, tm_yday=6, tm_isdst=0) 반환

time.asctime()

time.localtime가 리턴된 튜플 형태의 값을 인수로 받아서 날짜와 시간을 알아보기 쉽게 반환

import time
print(time.asctime(time.localtime(time.time()))) # Mon Jan  6 14:57:19 2025 반환
print(time.ctime()) # time.asctime(time.localtime(time.time()))와 동일

time.strftime()

시간과 관련하여 세밀하게 표현하는 여러 포맷 코드 제공

import time
print(time.strftime('%x', time.localtime(time.time()))) # 01/06/25
print(time.strftime('%X', time.localtime(time.time()))) # 15:06:14

time.sleep(seconds)

프로그램 실행을 seconds초 동안 일시 중단(지연)

-------------🐢--

math

수학 연산을 위한 함수들을 제공하는 모듈

math.sqrt(x), math.pow(x, y), math.exp(x), math.log(x[, base])

삼각함수

sin, cos, tan, asin, acos, atan …

상수

math.pi, math.e

정수/소수 관련

math.factorial(n), math.gcd(a, b): 최대 공약수, math.lcm(a, b): 최소 공배수

올림/내림

floor(x), ceil(x)

------------🐢---

random

난수 생성과 무작위 작업을 위한 함수들을 제공하는 모듈

random.random()

0 이상 1 미만의 실수 난수를 반환

random.randint(a, b)

a 이상 b 이하의 정수 난수 반환

import random
def random_data(data):
    num = random.randint(0, len(data) - 1)
    return data.pop(num)

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    while data:
        print(random_data(data))

random.choice(seq)

시퀀스(예: 리스트)에서 임의의 요소를 하나 선택

random.shuffle(seq)

시퀀스(리스트)의 요소들을 제자리에서 무작위로 섞음

random.sample(population, k)

모집단에서 중복 없이 k개의 요소를 랜덤 추출

-----------🐢---

itertools

효율적인 반복(iteration)을 위한 함수를 제공하는 모듈

itertools.count(start=0, step=1)

무한 등차수열 생성

itertools.cycle(iterable)

이터러블을 무한 반복

itertools.repeat(object, times=None)

object를 times번 (혹은 무한히) 반복 제공

itertools.permutations(iterable, r=None)

r 길이의 순열을 생성

itertools.combinations(iterable, r)

r 길이의 조합을 생성

 # 같은 숫자를 허용하는 중복 조합은 itertools.combinations_with_replacement() 

itertools.accumulate(iterable, func=operator.add)

누적 값을 만들어 나가는 이터레이터

itertools.zip_longest(*iterables, fillvalue=None)

전달한 반복 가능 객체의 길이가 서로 다르다면 긴 객체의 길이에 맞춰 fillvalue로 채움

----------🐢----

functools

고차 함수(Higher-order functions)나 함수를 다루는 유틸리티를 제공하는 모듈

functools.partial(func, *args, **kwargs)

특정 인자를 고정한 새 함수를 생성

from functools import partial
def add(a, b): return a + b
add_five = partial(add, 5)  # b만 받는 함수

functools.reduce(func, iterable, initializer=None)

시퀀스 원소를 누적 적용해 단일 값으로 축소

---------🐢-----

operator.itemgetter

operator 모듈 내의 **itemgetter**는 시퀀스나 매핑(딕셔너리)에서 특정 인덱스나 키를 기준으로 아이템을 꺼내는 함수

주로 정렬이나 정렬 키 함수(key 매개변수)로 많이 쓰임

from operator import itemgetter

data = [('banana', 2), ('apple', 5), ('cherry', 1)]
data_sorted = sorted(data, key=itemgetter(1))  # 두 번째 요소(수량)를 기준으로 정렬
# data_sorted -> [('cherry', 1), ('banana', 2), ('apple', 5)]

 # 만약 튜플이 아닌 어떤 클래스의 객체라면 attrgetter()를 적용하여 정렬

 sorted(data, key=attrgetter('age'))

--------🐢------

shutil

파일 연산(복사, 이동, 압축, 디렉터리 트리 삭제 등)을 위한 함수들을 제공하는 모듈

shutil.copy(src, dst)

파일을 복사

shutil.move(src, dst)

파일 또는 디렉터리를 이동(또는 이름 변경)

shutil.rmtree(path)

디렉터리 트리 전체를 제거

shutil.make_archive(base_name, format, root_dir='.')

파일들을 압축(아카이브)

-------🐢-------

glob

파일 경로 패턴 매칭을 도와주는 모듈

glob.glob(pattern, recursive=False)

와일드카드(*, ?, [...])를 사용한 파일/디렉터리 목록을 리스트로 반환

import glob
txt_files = glob.glob('*.txt')

------🐢--------

pickle

객체의 형태를 그대로 유지하면서 파일에 저장하고 불러올 수 있게 하는 모듈

pickle.dump(obj, file)

obj 객체를 이진 포맷으로 file에 저장

pickle.load(file)

file에서 피클화된 객체를 읽어 복원

-----🐢---------

os

운영 체제와 상호작용하기 위한 다양한 함수들을 제공(환경 변수, 파일/디렉터리 조작, 프로세스 정보 등)

os.environ

시스템 환경 변수를 담고 있는 사전형 객체

os.chdir(path), os.getcwd()

현재 작업 디렉터리를 변경/확인

os.listdir(path)

디렉터리 내 파일 및 폴더 목록 반환

os.mkdir(path)

디렉터리 생성

os.remove(path), os.rmdir(path)

파일 또는 디렉터리 삭제

os.path

파일 경로 처리

----🐢----------

zipfile

ZIP 아카이브를 읽고 쓰는 기능을 제공하는 모듈

ZipFile(file, mode='r', ...)

ZIP 아카이브를 열어서 파일을 읽거나 쓰기 가능

import zipfile

with zipfile.ZipFile('archive.zip', 'r') as zf:
    zf.extractall('dest_folder') # 모든 파일 해제 .extract는 특정 파일 해제

ZipFile.write(filename, arcname=None, compress_type=None)

ZIP에 파일 추가

---🐢-----------

tempfile

임시 파일과 임시 디렉터리를 손쉽게 만들고 관리하는 모듈

tempfile.mkstemp()

자동으로 임시 파일을 만들고, 닫히면 삭제

tempfile.TemporaryFile()

임시 저장 공간으로 사용할 파일 객체 리턴

tempfile.TemporaryDirectory()

임시 디렉터리를 생성, 블록을 벗어나면 자동 삭제

--🐢------------

traceback

예외(에러) 발생 시의 스택 트레이스를 관리하고, 형식을 지정해 출력할 수 있는 모듈

traceback.print_exc()

현재 예외의 스택 트레이스를 표준 에러로 출력

traceback.format_exc()

예외 정보를 문자열로 반환

-🐢-------------

urllib

URL 읽고 분석, 요청/응답을 다루는 모듈들의 집합(HTTP, FTP 등)

urllib.request

URL 열기(다운로드), GET/POST 요청 전송, HTTP 헤더 수정 등

import urllib.request

response = urllib.request.urlopen('https://example.com')
html = response.read().decode('utf-8')

urllib.parse

URL 인코딩/디코딩(quote, unquote 등), URL 파싱(urlparse) 등

urllib.error

예외 처리(URLError, HTTPError)

🐢--------------

webbrowser

시스템에 설치된 기본 웹 브라우저를 자동으로 열거나 특정 URL을 열도록 할 수 있는 모듈

webbrowser.open(url, new=0, autoraise=True)

기본 웹 브라우저에서 URL 열기

webbrowser.open_new(url), webbrowser.open_new_tab(url)

새 창이나 새 탭 열기

import webbrowser
webbrowser.open("https://www.python.org")
저작자표시 비영리 변경금지 (새창열림)

'언어 > Python' 카테고리의 다른 글

유니코드 문자열  (1) 2025.01.08
Threading 모듈  (0) 2025.01.07
파이썬 내장 함수  (0) 2025.01.05
예외 처리  (0) 2025.01.02
패키지(Package)  (2) 2025.01.01
'언어/Python' 카테고리의 다른 글
  • 유니코드 문자열
  • Threading 모듈
  • 파이썬 내장 함수
  • 예외 처리
우는거북이
우는거북이
  • 우는거북이
    거북이는 울고 있다
    우는거북이
  • 전체
    오늘
    어제
    • 알아보기 (74) N
      • AI (4)
      • 언어 (16)
        • Python (15)
        • C언어 (1)
      • 알고리즘 (7)
      • 백준 (22)
      • 자료구조 (10)
      • 컴퓨터네트워크 (6)
      • 운영체제 (1)
      • 데이터통신 (8) N
  • 인기 글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
우는거북이
표준 라이브러리
상단으로

티스토리툴바