Sign In

[Python] 라이브러리

Y
Yerim
  1. Python

표준 라이브러리

자주 사용되는 표준 라이브러리

1.
os 모듈: 운영체제와 상호작용하는 데 사용되는 함수들을 제공
2.
sys모듈: Python 인터프리터와 상호작용하는 도구를 제공
3.
math 모듈: 수학적인 연산을 수행하는데 필요한 함수들을 제공
4.
datetime 모듈: 날짜와 시간을 다루는 클래스를 제공
5.
json 모듈: JSON 형식의 데이터를 읽고 쓰는 데 사용
6.
collections 모듈: 기본 데이터 컨테이너 외에도 다양한 데이터 컨테이너 타입 제공
7.
requests 모듈: HTTP 요청을 쉽게 보낼 수 있는 기능을 제공

os

import os

# os.environ: 시스템 내의 환경 변숫값
print(os.environ) 

# os.chdir: 디렉터리 위치 변경
os.chdir("C:\WINDOWS")

# os.getcwd: 디렉터리 위치 돌려받기
os.getcwd()

# os.system: 시스템 명령어 호출
os.system("dir")

# os.popen: 실행한 시스템 명령어의 결괏값 반환
f = os.popen("dir") # 읽기 모드 형태의 파일 객체로 리턴 
print(f.read())     # 객체의 내용 확인
함수
설명
os.mkdir(디렉터리)
디렉터리를 생성한다.
os.rmdir(디렉터리)
디렉터리를 삭제한다. 단, 디렉터리가 비어 있어야 삭제할 수 있다.
os.remove(파일)
파일을 지운다.
os.rename(src, dst)
src라는 이름의 파일을 dst라는 이름으로 바꾼다.

math

math.gcd - 최대 공약수
import math
math.gcd(60, 100, 80) # 20
math.lcm - 최소공배수
math.lcm(15, 25) # 75

datetime

import datetime

# datetime 객체: 연, 월 일을 인수로  날짜 객체
day1 = datetime.date(2021, 12, 14) 
day2 = datetime.date(2023, 4, 5)

# 날짜 객체의 차이
diff = day2 - day1
# 정보 추출
now = datetime.datetime.now() # 현재 날짜와 시간
date = now.date()             # 날짜 정보 추출
print('datetime 객체에서 추출된 date 객체: ', date.strftime("%Y년 %m월 %d일"))

# datetime 객체 속성 변경
new_date = now.replace(year=2022, month=1, day=1, hour=0, minute=0, second=0)
print('변경된 datetime 객체:', new_date)

# 요일 정보
weekday_str = ['월', '화', '수', '목', '금', '토', '일']
print('현재 날짜의 요일', weekday_str[now.weekday()]) # 0: 월요일 ~ 6: 일요일
print('현재 날짜의 ISO 요일: ', now.isoweekday()) # 1: 월요일 ~ 7: 일요일

# datetime 객체를 UNIX timestamp로 변환
print('datetime 객체의 timestamp 값:', now.timestamp())

# datetime 객체의 시간대 변경
# tz: 변경하려는 시간대를 나타내는 tzinfo 객체
import pytz
new_timezone = pytz.timezone("Asia/Seoul")
print('변경된 datetime 객체: ', now.astimezone(tz=new_timezone) )

# 두 날짜 또는 시간 간격
print("2시간 뒤의 시간: ", now + datetime.timedelta(hours=2))
print("3일 전의 시간: ", now - datetime.timedelta(days=3))

json

import json

# json 파일 오픈
with open('myinfo.json') as f:
    data = json.load(f)

외부 라이브러리

pip

•
파이썬 모듈이나 패키지를 쉽게 설치할 수 있는 도구
•
파이썬 프로그램을 설치하면 의존성 있는 모듈이나 패키지를 함께 설치해주어 편리
# 패키지 설치
pip install PackageName

# 특정 버전으로 설치
pip install PackageName==1.0.4

# 최신 버전으로 업그레이드
pip install --upgrade PackageName

# 패키지 삭제
pip uninstall PckageName

# 설치된 패키지 확인
pip list

Faker

•
테스트용 가짜 데이터를 생성할 때 사용하는 라이브러리
항목
설명
fake.name()
이름
fake.address()
주소
fake.postcode()
우편 번호
fake.country()
국가명
fake.company()
회사명
fake.job()
직업명
fake.phone_number()
휴대전화 번호
fake.email()
이메일 주소
fake.user_name()
사용자명
fake.pyint(min_value=0, max_value=100)
0부터 100 사이의 임의의 숫자
fake.ipv4_private()
IP 주소
fake.text()
임의의 문장 (한글 임의의 문장은 fake.catch_phrase() 사용)
fake.color_name()
색상명
Yerim-DevNote
Subscribe to 'Yerim-DevNote'
Subscribe to my site to be the first to receive notifications and emails about the latest updates, including new posts.
Join Slashpage and subscribe to 'Yerim-DevNote'!
Subscribe
👍