Python의 표준 라이브러리에 대해 알아봅니다.
datetime.date: 연, 월, 일로 날짜를 표현할 때 사용하는 함수. day1 = datetime.date(2021, 12, 14) # 2021-12-14
day2 = datetime.date(2023, 4, 5)객체.daysdiff = day2 - day1
diff.days # 477day = datetime.date(2021, 12, 14)
day.weekday() # 1```python
day = datetime.date(2021, 12, 14)
day.isoweekday() # 2
```time.time(): UTC(universal time coordinated, 협정 세계 표준시)를 사용하여 현재 시간을 실수 형태로 반환하는 함수. time.time() # 1684983953.5221913
time.localtime: time.time()이 반환한 실숫값을 사용해서 연, 월, 일, 시, 분, 초, ... 의 형태로 바꾸어 주는 함수.time.localtime(time.time())
# time.struct_time(tm_year=2023, tm_mon=5, tm_mday=21, tm_hour=16, tm_min=48, tm_sec=42, tm_wday=1, tm_yday=141, tm_isdst=0)
time.asctime: time.localtime가 반환된 튜플 형태의 값을 인수로 받아서 날짜와 시간을 알아보기 쉬운 형태로 반환하는 함수.time.asctime(time.localtime(time.time()))
# 'Fri Apr 28 20:50:20 2023'
time.ctime(): time.asctime(time.localtime(time.time()))을 간단하게. time.ctime()
# 'Fri Apr 28 20:56:31 2023'
time.strftime('출력할 형식 포맷 코드', time.localtime(time.time()))time.strftime('%x', time.localtime(time.time()))
# '05/25/23'
time.strftime('%c', time.localtime(time.time()))
# 'Thu May 25 10:13:52 2023'
time.sleep: 일정한 시간 간격을 두고 루프를 실행할 수 있다.# 1초 간격으로 0부터 9까지의 숫자를 출력
for i in range(10):
print(i)
time.sleep(1)
math.gcd(60, 100, 80) # 20
math.lcm(15, 25) # 75
random()random.random() # 0.53840103305098674random.randint(1, 10) # 6choice(리스트, 무작위로 추출할 원소의 개수): 입력으로 받은 리스트에서 무작위로 하나를 선택하여 반환.data = [1, 2, 3, 4, 5]
random.sample(data, len(data)) # [5, 1, 3, 4, 2]itertools.zip_longest(*iterables, fillvalue=None)students = ['한민서', '황지민', '이영철', '이광수', '김승민']
snacks = ['사탕', '초컬릿', '젤리']
result = zip(students, snacks)
print(list(result)) # [('한민서', '사탕'), ('황지민', '초컬릿'), ('이영철', '젤리')]
result = itertools.zip_longest(students, snacks, fillvalue='새우깡')
print(list(result)) # [('한민서', '사탕'), ('황지민', '초콜릿'), ('이영철', '젤리'), ('이광수', '새우깡'), ('김승민', '새우깡')]
itertools.permutations(iterable, r)list(itertools.permutations(['1', '2', '3'], 2))
# [('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', '2')]itertools.permutations(iterable, r)list(itertools.combinations(['1', '2', '3'], 2))
# [('1', '2'), ('1', '3'), ('2', '3')]itertools.combinations_with_replacement()len(list(itertools.combinations_with_replacement(range(1, 46), 6)))
# 15890700functools.reduce(function, iterable)data = [1, 2, 3, 4, 5]
result = functools.reduce(lambda x, y: x + y, data)
print(result) # 15
# functools.reduce()로 최댓값 구하기
num_list = [3, 2, 8, 1, 6, 7]
max_num = functools.reduce(lambda x, y: x if x > y else y, num_list)
print(max_num) # 8 출력
주로 sorted와 같은 함수의 key 매개변수에 적용하여 다양한 기준으로 정렬할 수 있도록 도와준다.
리스트
from operator import itemgetter
students = [
("jane", 22, 'A'),
("dave", 32, 'B'),
("sally", 17, 'B'),
]
result = sorted(students, key=itemgetter(1))
# [('sally', 17, 'B'), ('jane', 22, 'A'), ('dave', 32, 'B')]
딕셔너리
from operator import itemgetter
students = [
{"name": "jane", "age": 22, "grade": 'A'},
{"name": "dave", "age": 32, "grade": 'B'},
{"name": "sally", "age": 17, "grade": 'B'},
]
result = sorted(students, key=itemgetter('age'))
# [{'name': 'sally', 'age': 17, 'grade': 'B'}, {'name': 'jane', 'age': 22, 'grade': 'A'}, {'name': 'dave', 'age': 32, 'grade': 'B'}]
from operator import attrgetter
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
students = [
Student('jane', 22, 'A'),
Student('dave', 32, 'B'),
Student('sally', 17, 'B'),
]
result = sorted(students, key=attrgetter('age'))
shutil.copyshutil.moveshutil.copy("c:/doit/a.txt", "c:/temp/a.txt.bak") # c:\doit\a.txt를 c:\temp\a.txt.bak이라는 이름으로 복사
shutil.move("c:/doit/a.txt", "c:/temp/a.txt") # 이동
-glob(pathname): 디렉터리에 있는 파일들을 리스트로 만들기.
import glob
glob.glob("c:/doit/mark*")
# ['c:/doit\\marks1.py', 'c:/doit\\marks2.py', 'c:/doit\\marks3.py']
pickle.dump: 딕셔너리 객체인 data를 그대로 파일에 저장.import pickle
f = open("test.txt", 'wb')
data = {1: 'python', 2: 'you need'}
pickle.dump(data, f)
f.close()
pickle.load: 원래 있던 딕셔너리 객체(data) 상태 그대로 불러온다.import pickle
f = open("test.txt", 'rb')
data = pickle.load(f)
print(data) # {2:'you need', 1:'python'}
os.environ
# environ({'PROGRAMFILES': 'C:\\Program Files', 'APPDATA': … 생략 …})
# 반환받은 객체를 호출하여 사용
os.environ['PATH']
# 'C:\\ProgramData\\Oracle\\Java\\javapath;...생략...'
os.chdir("C:\WINDOWS")
os.getcwd() # 'C:\WINDOWS'
os.system("명령어"): 시스템 명령어 호출.os.system("dir")
f = os.popen("dir")
print(f.read()) # 객체 읽기
os.mkdir(디렉터리): 디렉터리를 생성.os.rmdir(디렉터리): 디렉터리를 삭제. 단, 디렉터리가 비어 있어야 삭제할 수 있다.os.remove(파일): 파일을 지운다.os.rename(src, dst): src라는 이름의 파일을 dst라는 이름으로 바꾼다.threading.Thread(): 스레드 생성.start(): 스레드 실행.join(): 해당 스레드가 종료될 때까지 기다리게 한다.# thread_test.py
import time
import threading
def long_task():
for i in range(5):
time.sleep(1)
print("working:%s\n" % i)
print("Start")
threads = []
for i in range(5): # long_task를 5회 수행
t = threading.Thread(target=long_task) # 스레드 생성
threads.append(t)
for t in threads:
t.start() # 스레드 실행
for t in threads:
t.join() # join으로 스레드가 종료될때까지 기다린다.
print("End")
traceback.format_exc(): 오류 추적 결과를 문자열로 반환하는 함수.import traceback
def a():
return 1/0
def b():
a()
def main():
try:
b()
except:
print("오류가 발생했습니다.")
print(traceback.format_exc())
main()
# 오류가 발생했습니다.
# Traceback (most recent call last):
# File "c:\doit\traceback_sample.py", line 14, in main
# b()
# File "c:\doit\traceback_sample.py", # line 9, in b
# a()
# File "c:\doit\traceback_sample.py", line 5, in a
# return 1/0
# ZeroDivisionError: division by zero
json.load(파일_객체): JSON 파일을 읽어 데이터를 딕셔너리 자료형으로 반환.with open('myinfo.json') as f:
data = json.load(f)
type(data) # <class 'dict'>
data # {'name': '홍길동', 'birth': '0525', 'age': 30}
json.dump(딕셔너리, 파일_객체): 딕셔너리 자료형을 JSON 파일로 생성.data = {'name': '홍길동', 'birth': '0525', 'age': 30}
with open('myinfo.json', 'w') as f:
json.dump(data, f)
json.dumps(): 파이썬 자료형을 JSON 문자열로.json.loads(): JSON 문자열을 딕셔너리로 다시 역변환.d = {"name":"홍길동", "birth":"0525", "age": 30}
json_data = json.dumps(d)
json_data # '{"name": "\\ud64d\\uae38\\ub3d9", "birth": "0525", "age": 30}'
json.loads(json_data)
# {'name': '홍길동', 'birth': '0525', 'age': 30}
# ensure_ascii=False 옵션
json_data = json.dumps(d, ensure_ascii=False)
json_data # '{"name": "홍길동", "birth": "0525", "age": 30}'
json.loads(json_data)
# {'name': '홍길동', 'birth': '0525', 'age': 30}
# indent 옵션
print(json.dumps(d, indent=2, ensure_ascii=False))
# {
# "name": "홍길동",
# "birth": "0525",
# "age": 30
# }
# 리스트나 튜플처럼 다른 자료형도 JSON 문자열로 바꿀 수 있다.
json.dumps([1,2,3]) # '[1, 2, 3]'
json.dumps((4,5,6)) # '[4, 5, 6]'
webbrowser.open_new('http://python.org'): 새창으로 열기.webbrowser.open('http://python.org'): 이미 열린 브라우저로 원하는 사이트를 열고 싶다면.