본문 바로가기
파이썬

파이썬 표준 라이브러리 소개

by python pro 2023. 1. 25.
반응형

 

파이썬은 풍부한 표준 라이브러리를 가지고 있어, 다양한 작업을 쉽게 수행할 수 있습니다. 이 표준 라이브러리는 파이썬 설치 시 기본적으로 제공되며, 추가로 설치할 필요 없이 사용이 가능합니다.

os 모듈

os 모듈은 운영체제와 관련된 기능을 제공합니다. 예를 들어, 현재 작업 디렉토리를 확인하거나 파일을 생성, 삭제하는 것이 가능합니다.

import os

# 현재 작업 디렉토리 확인
print(os.getcwd())

# 파일 생성
with open("test.txt", "w") as file:
    file.write("Hello World!")

# 파일 삭제
os.remove("test.txt")

math 모듈

math 모듈은 수학 관련 기능을 제공합니다. 예를 들어, 삼각함수, 지수, 로그 등의 수학 함수를 사용할 수 있습니다.

import math

# 원의 넓이 구하기
print(math.pi * math.pow(2, 2))

# 제곱근 구하기
print(math.sqrt(16))

# 올림
print(math.ceil(3.14))

# 내림
print(math.floor(3.14))

random 모듈

random 모듈은 난수(random number)를 생성하는 기능을 제공합니다. 예를 들어, 난수를 사용하여 로또 번호를 생성하거나, 무작위로 선택된 아이템을 구할 수 있습니다.

import random

# 1~10 사이의 난수 생성
print(random.randint(1, 10))

# 리스트 안에서 무작위로 아이템 선택
items = [1, 2, 3, 4, 5]
print(random.choice(items))

# 리스트 안에서 여러 아이템 무작위로 선택
print(random.sample(items, 2))

datetime 모듈

datetime 모듈을 사용하여 현재 시간을 확인하거나, 날짜 계산을 할 수 있습니다.

from datetime import datetime, timedelta

# 현재 시간 확인
now = datetime.now()
print(now)

# 날짜 계산
one_day = timedelta(days=1)
tomorrow = now + one_day
print(tomorrow)

CSV 모듈

csv 모듈을 사용하여 CSV 파일을 읽고 쓸 수 있습니다.

import csv

# CSV 파일 읽기
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# CSV 파일 쓰기
with open('data.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Name', 'Age', 'Gender'])
    writer.writerow(['John', '30', 'Male'])
    writer.writerow(['Emily', '25', 'Female'])

json 모듈

json` 모듈을 사용하여 JSON 데이터를 읽고 쓸 수 있습니다.

import json

# JSON 파일 읽기
with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)

# JSON 파일 쓰기
data = {
    "Name": "John",
    "Age": 30,
    "Gender": "Male"
}

with open('data.json', 'w') as file:
    json.dump(data, file)

shutil 모듈

shutil 모듈은 파일 복사, 이동, 삭제를 할 수 있습니다.

import shutil

# 파일 복사
shutil.copy("original.txt", "copy.txt")

# 파일 이동
shutil.move("original.txt", "moved.txt")

# 파일 삭제
shutil.remove("moved.txt")

glob 모듈

glob 모듈은 파일 이름을 패턴에 맞게 검색할 수 있습니다.

import glob

# 파일 검색
files = glob.glob("*.txt")
print(files)

os.path 모듈

os.path 모듈은 파일 경로를 조작할 수 있습니다. 예를 들어, 파일의 확장자를 구하거나, 파일의 존재 여부를 확인할 수 있습니다.

import os.path

# 파일 확장자 구하기
file_name = "example.txt"
print(os.path.splitext(file_name)[1])

# 파일 존재 여부 확인
print(os.path.exists(file_name))
반응형

'파이썬' 카테고리의 다른 글

파이썬 dictionary comprehension  (0) 2023.01.25
파이썬 list comprehension  (0) 2023.01.25
파이썬 정규표현식, 정규식  (0) 2023.01.25
파이썬 입력과 출력  (0) 2023.01.25
파이썬 문자열 관련 함수  (0) 2023.01.24

댓글