라이브러리

매일 공부(ML)·2021년 11월 25일
0

Python

목록 보기
9/38

파이썬 라이브러리

sys

  • 정의: 변수와 함수를 직접 제어 가능

  • sys.argv : 명령 행에서 인수 전달

C:/User/home>python test.py abc pey guido #test.py 뒤의 값들이 리스트에 추가

import sys
print(sys.argv)

C:/doit/Mymod>python argv_test.py you need python #['argv_test.py', 'you', 'need', 'python']
  • sys.exit(): 강제로 스크립트 종료

  • sys.path(): 자신이 만든 모듈 불러와 사용하기

import sys # '': 현재 디렉토리
sys.path # ['', 'C:\\Windows\\SYSTEM32\\python37.zip', 'c:\\Python37\\DLLs', 
'c:\\Python37\\lib', 'c:\\Python37', 'c:\\Python37\\lib\\site-packages']
>>>

pickle

  • 정의: 객체의 형태를 그대로 유지하면서 파일 저장한 후 불러오기 가능
# 딕셔너리 객체에 그대로 저장
import pickle
f = open("test.txt", 'wb')
data = {1: 'python', 2: 'you need'}
pickle.dump(data, f)
f.close()

# 저장 파일 불러오기

import pickle
f = open("test.txt", 'rb')
data = pickle.load(f)
print(data) # {2:'you need', 1:'python'}

OS

  • os.environ: 내 시스템의 환경 변수 값을 알고 싶을 때
import os
os.environ # environ({'PROGRAMFILES': 'C:\\Program Files', 'APPDATA': … 생략 …})
  • os.chdir : 디렉토리 위치 변경하기
os.chdir("C:\WINDOWS")
  • os.getcwd: 현재 자신의 디렉토리 위치 돌려줌
os.getcwd() # 'C:\WINDOWS'
  • os.system(): 시스템 자체의 프로그램이나 기타 명령어 호출ㄹ
os.system("dir")
  • os.popen() : 실행한 시스템 명령어의 결과값 돌려받기
f = os.popen("dir")
print(f.read())
  • os.mkdir() : 디렉토리 생성

  • os.rmdir() : 비어있는 디렉터리 삭제

  • os.unlink() : 파일 지우기

  • os.rename(src, dst) : src라는 이름의 파일을 dst로 바꾼다

shutil

  • 파일 복사해주는 모듈
import shutil
shutil.copy("src.txt", "dst.txt")

glob

  • 특정 디렉토리에 있는 파일 이름 알려줌

  • glob(pathname) : 디렉터리에 있는 파일들을 리스트로 만들기

import glob
glob.glob("c:/doit/mark*") # ['c:/doit\\marks1.py', 'c:/doit\\marks2.py', 'c:/doit\\marks3.py']
>>>

tempfile

  • 파일 임시로 만든다
import tempfile
filename = tempfile.mkstemp() #중복되지 않는 임시 파일의 이름을 만들어 준다.
filename # 'C:\WINDOWS\TEMP\~-275151-0'

import tempfile
f = tempfile.TemporaryFile() # 저장공간으로 사용할 파일 객체 돌려준다
f.close()

time

  • time.time: 현재 시간을 실수 형태로 돌려주는 함수
import time
time.time() # 988458015.73417199
  • time.localtime : time.time()이 돌려준 실수 값을 사용하여 연도,월,일,시,분,초의 형태로 바꾼다
time.localtime(time.time()) # time.struct_time(tm_year=2013, 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())) #'Sat Apr 28 20:50:20 2001'
  • time.ctime(): 현재 시간만 돌려준다
time.ctime() # 'Sat Apr 28 20:56:31 2001'
  • time.strftime(): 시간에 관계된 세밀한 포맷코드 제공
time.strftime('출력할 형식 포맷 코드', time.localtime(time.time()))


import time
time.strftime('%x', time.localtime(time.time())) # '05/01/01'
time.strftime('%c', time.localtime(time.time())) #'05/01/01 17:22:21'
  • time.sleep(): 일정간격으로 루프 안에서 사용하는 것이다.
import time
for i in range(10):
    print(i)
    time.sleep(1)

calendat

  • 달력을 볼 수 있게 해준다.

  • calendar.calendat(연도): 그 해 전체 달력 보기 가능


import calendar
print(calendar.calendar(2015))
  • calendar.weekday(연도, 월, 일): 그 날짜에 해당하는 요일 정보 돌려준다.

    • 월요일은 0, 화요일은 1, 수요일은 2, 목요일은 3, 금요일은 4, 토요일은 5, 일요일은 6
calendar.weekday(2015, 12, 31) # 3
  • calendar.monthrange(연도,월) : 입력받은 달의 1일 무슨 요일인지와 몇 일까지 있는지 알려준다
calendar.monthrange(2015,12) # (1, 31)

random

  • 정의: 난수를 발생시키는 모듈
import random
random.random() # 0.53840103305098674
  • 예시
import random
def random_pop(data):
    number = random.randint(0, len(data)-1)
    return data.pop(number)

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]
    while data: 
        print(random_pop(data))
       
  • random.shuffle() 리스트 항목 무작위로 섞기
import random
data = [1, 2, 3, 4, 5]
random.shuffle(data)
data

webbroser

  • 기본 웹 브라우저 자동 실행

    webbrowser.open_new("http://google.com")
profile
성장을 도울 아카이빙 블로그

0개의 댓글