스터디/혼자공부하는파이썬
chapter07. 모듈(1)
냠냠쿠
2024. 4. 23. 20:21
728x90
1. 모듈
(1) 표준모듈 : 기본적으로 내장
(2) 외부 모듈 : 다른 사람들이 만들어 공개한 모듈
사용방법
import 모듈이름
2. 내부모듈
1) math모듈
#math모듈
import math
math.sin(1) #사인
math.cos(1) #코사인
math.tan(1) #탄젠트
math.floor(5.4) #내림
math.ceil(4.1) #올림
- 반올림은 round() 사용
2) form구문
from math import sin, cos, tan, floor, ceil
sin(1)
cos(1)
전부 import 하지 않고 일부만 import하는 방법
3) as 구문
import math as m
m.sin(1)
m.cos(1)
모듈의 이름을 재정의하여 사용하고싶을 때
4) random 모듈
import random
print(random.random())
#uniform(min,max)
print(random.uniform(10,20))
#randerage() 지정한 범위
#randerage(max)
#randerage(min, max)
print(random.randrange(10))
print(random.randrange(10,20))
#랜덤선택
print(random.choice([1,2,3,4]))
#랜덤 섞기
print(random.shuffle([1,2,3,4]))
#sample(list,k=n) 리스트중 n개 뽑기
print(random.sample([1,2,3,4], k=2))
5) sys 모듈
import sys
#명령 매개변수
print(sys.argv)
#컴퓨터 환경 정보 출력
print(sys.getwindowsversion())
print(sys.copyright)
print(sys.version)
#프로그램 강종
sys.exit()
sys.argv는 명령 매개변수로 프로그램을 실행할 때 추가로 입력하는 값을 의미
명령 프롬프트 창의 경로와 실행할 .py 파일 위치는 반드시 일치해야한다.
6) OS 모듈
import os
#현재 운영체제
print(os.name)
#현재 폴더
print(os.getcwd())
#폴더 내부요소
print(os.listdir())
#폴더만들기 및 삭제
os.mkdir("ㅎㅇ")
os.rmdir("ㅎㅇ")
#파일생성 + 이름변경
with open("ㅎㅇ.txt", "w") as file:
file.write("내용입니다")
os.rename("ㅎㅇ.txt", "새이름.txt")
#파일제거
os.remove("새이름.txt")
#시스템 명령어 실행
os.system("dir")
os.system() 함수는 rm -rf / 와같은 명령어를 실행 했을 때 루트 권한이 있는 경우 컴퓨터의 모든 것을 삭제하기 때문에 매우 조심해야한다.
#현재 디렉터리를 읽어 파일인지 디렉터리인지 구분하기
import os
output = os.listdir(".")
#파일/폴더 구분
for path in ourput:
if os.path.isdir(path):
print("폴더:", path)
else:
print("파일:", path)
#재귀함수로 현재 폴더에있는 모든 파일을 탐색하기
import os
def read_folder(path):
#폴더 요소 읽기
output = os.listfir(path)
for item in output:
#폴더라면 계속 읽기
if os.path.isdir(item):
read_folder(item)
#파일이라면 출력하기
else
print(item)
#현재 폴더의 파일/폴더 출력
read_folder(".")
7) datetime 모듈
import datetime
now = datetime.datetime.now()
print(now.year)
#포맷에 맞춰 출력
output_1 = now.strftime("%Y.%m.%d %H:%M:%S")
output_2 = "{}년 {}월 {}일 {}시 {}분 {}초".format(now.year, now.month, now.day, now.hour, now.minute, now.second)
output_3 = now.strftime("%Y.%m.%d %H:%M:%S").format(*"년월일시분초")
print(output_1)
print(output_2)
print(output_3)
특정 시간 이후를 구할 때에는 now + datetime.timedelta(weeks=1) 등과같이 사용한다.
특정 시간 요소를 교체할 때에는 replace를 사용한다 ex) now.replace(year=(now.year+1))
8) time 모듈
import time
#프로그램 10초간 정지
time.sleep(10)
9) urllib 모듈
- URL을 다루는 라이브러리
from urllib import request
target =request.urlopen("https://www.naver.com")
output = target.read()
print(output)
read()함수를 사용하면 웹 페이지 내용을 읽어 html 내용을 읽어서 가져온다
10) operator.itemgetter()함수
- 딕셔너리 형태의 리스트에서 최솟값, 최댓값을 람다로 구하기
from operator import itemgetter
books = [{
"제목" : "혼자 공부하는 파이썬",
"가격" : 18000
}, {
"제목" : "혼자 공부하는 자바",
"가격" : 17000
}, {
"제목" : "혼자 공부하는 머신러닝",
"가격" : 10000
}]
print(min(books, key=itemgetter("가격")))
print(max(books, key=itemgetter("가격")))
728x90