혼공학습단/혼자 공부하는 파이썬

[혼공학습단 파이썬] #7-1. 표준 모듈(math, random, sys, datetime, urllib, os)

✨️데이터분석가✨️ 2023. 8. 12. 22:55
728x90
728x90
7. 모듈
    1) 표준 모듈
         (1) math 모듈
         (2) as 구문
         (3) from 구문

         (4) random 모듈

         (5) sys 모듈
         (6) datetime 모듈
         (7) time 모듈
         (8) urllib 모듈
         (9) os 모듈

 

1) 표준 모듈

- 모듈: 여러 변수와 함수를 가지고 있는 집합체

- 표준 모듈: 파이썬이 기본으로 제공하는 모듈

- import 모듈명

* 'python documentation' - 'Library reference'에서 세부 모듈 확인 가능

 

 

(1) math 모듈

- 수학 관련 기능을 제공하는 모듈

sin(x) cos(x) tan(x) log(x[, base]) ceil(x) floor(x)
사인값 코사인값 탄젠트값 로그값 올림 내림
import math
print(math.sin(5))
더보기

# 실행결과

-0.9589242746631385

 

 

(2) as 구문

- 모듈명을 원하는 명칭으로 지정하는 구문

- import 모듈명 as 사용하고 싶은 식별자 

import math as m
print(m.sin(5))
더보기

# 실행결과

-0.9589242746631385

 

 

(3) from 구문

- 앞에 모듈명을 작성하지 않을 수 있도록 하는 구문

- from 모듈명 import 사용하고 싶은 변수/함수

- from 모듈명 import * : 해당 모듈에 속하는 모든 변수/함수

from math import sin, ceil
print(ceil(5.3))
from math import *
print(floor(5.3))
더보기

# 실행결과

5

6

 

 

(4) random 모듈

- 랜덤 값을 생성하는 모듈

- random(): 랜덤 숫자 출력 / uniform(min, max): 범위 사이 숫자 출력

import random
print(random.random())
print(random.uniform(1, 5))
더보기

# 실행결과

0.6488472252333601
1.7135879779187904

 

 

(5) sys 모듈

- 시스템 관련 모듈, *명령 매개변수를 받을 때 많이 사용

  * 명령 매개변수: sys.argv 

import sys
print(sys.argv)
더보기

# 실행결과

D:\혼공파이썬> python .\7_module.py
['.\\7_module.py']

# 실행결과

D:\혼공파이썬> python .\7_module.py 3 5 7
['.\\7_module.py', '3', '5', '7']

 

 

(6) datetime 모듈

- 날짜+시간 관련 모듈

- 현재 시각 출력

import datetime
now = datetime.datetime.now()

from datetime import datetime
now = datetime.now()
print("{}{}{}{}{}{}초".format(now.year,
    now.month, now.day, now.hour, now.minute, now.second))
더보기

# 실행결과

2023년 8월 12일 18시 28분 52초

 

- 특정 시점 출력

past = datetime(2000, 12, 31, 11, 30, 59)
print(past)
더보기

# 실행결과

2000-12-31 11:30:59

 

 

(7) time 모듈

- 시간 관련 모듈

- time.sleep(00): 특정 시간(00초) 동안 프로그램 실행을 정지하는 함수 

import time
print("A")
time.sleep(5)
print("B")
더보기

# 실행결과

A

B

→ A 출력 후, 5초 뒤에 B가 출력됨

 

 

(8) urllib 모듈

- URL을 다루는 라이브러리 모듈

- urlopen("http://"): URL 페이지를 열어주는 함수

from urllib import request
target = request.urlopen("http://hanbit.co.kr")
content = target.read()
print(content[:100])
더보기

# 실행결과

b'<!DOCTYPE html>\r\n<html lang="ko">\r\n<head>\r\n<!--[if lte IE 8]>\r\n<script>\r\n  location.replace(\'/suppor'

→ b로 시작, 바이너리 데이터를 의미

 

 

(9) os 모듈

- 운영체제 관련 모듈

- os.listdir(폴더 경로): 폴더 내 모든 것을 리스트로 출력

- os.path.isdir(경로): 경로에 있는 것이 폴더면 True

# 파일/폴더명 출력
import os
output = os.listdir(".")
print("os.listdir():", output)

# 파일/폴더 구분
for path in output:
    if os.path.isdir(path):
        print("폴더:", path)
    else:
        print("파일", path)
더보기

# 실행결과

os.listdir(): ['6_exception.py', '7_module.py']

파일 6_exception.py
파일 7_module.py

 

 

 

728x90
728x90