python/기본
-
Python Enumpython/기본 2022. 10. 21. 20:44
import enum @enum.unique class Status(enum.Enum): Active = 1 InActive = 2 class Permission(enum.IntFlag): R = 4 W = 2 X = 1 if __name__ == '__main__': print(Status.Active.value) # 1 print(Status(2)) # Status.InActive for s in Status: print(s) print(Permission.R | Permission.W) # Permission.R|W RW = Permission.R | Permission.W print(Permission.R in RW) # True print(Permission.X in RW) # False
-
Python Closurepython/기본 2022. 10. 21. 20:07
코드1 from typing import Callable def sum(x: int, y: int) -> Callable[[], int]: def runner(): out = x + y print(out) return out return runner if __name__ == '__main__': f = sum(1, 2) f() 코드2 functools.partial() 을 이용해 아래처럼 작성할 수 있다. import functools def sum(x: int, y: int) -> int: out = x + y print(out) return out if __name__ == '__main__': f = functools.partial(sum, 1, 2) f() 설명 scala 의 Closure 와 ..
-
datetime / timepython/기본 2022. 5. 2. 14:21
여기서는 standard library 로 제공되는 datetime 을 사용했지만 arrow 의 사용도 고민해 볼 만하다. import datetime now = datetime.datetime.now() print(now) # 2022-05-02 14:09:29.165956 print(now.isoformat()) # 2022-05-02T14:09:29.165956 print(now.strftime('%d/%m/%y-%H%M%S%f')) # 02/05/22-140929165956 today = datetime.date.today() print(today) # 2022-05-02 print(today.strftime('%d/%m/%y')) t = datetime.time(hour=1, minute=10,..
-
tempfile / subprocesspython/기본 2022. 5. 2. 14:04
import tempfile # 임시 디렉토리에서 압축을 푼다든지로 응용될 수 있음 with tempfile.TemporaryFile(mode='w+') as t: t.write('hello') t.seek(0) print(t.read()) # hello with tempfile.NamedTemporaryFile(delete=False) as t: print(t.name) with open(t.name, 'w+') as f: f.write('test\n') f.seek(0) print(f.read()) with tempfile.TemporaryDirectory() as td: print(td) ##############################################################..
-
tar / zippython/기본 2022. 5. 2. 13:39
import tarfile # tar.gz 파일 생성하기 with tarfile.open('test.tar.gz', 'w:gz') as tr: tr.add('test_dir') # tar.gz 파일 압축풀기 with tarfile.open('test.tar.gz', 'r:gz') as tr: tr.extractall(path='test_tar') # 특정 파일의 내용만 볼 때 with tr.extractfile('test_dir/sub_dir/sub_test.txt') as f: print(f.read()) #################################################################### import zipfile with zipfile.ZipFile('test...
-
os, pathlib, glob, shutilpython/기본 2022. 5. 1. 21:31
비슷하게 여러 라이브러리가 있지만 pathlib 를 추천함 import os print(os.path.exists('test.txt')) print(os.path.isfile('test.txt')) print(os.path.isdir('test.txt')) os.rename('test.txt', 'renamed.txt') os.symlink('renamed.txt', 'symlink.txt') os.mkdir('test_dir') os.rmdir('test_dir') # empty dir 일때만 삭제 가능 import pathlib pathlib.Path('empty.txt').touch() # empty file 생성 os.remove('empty.txt') ########################..