모듈

개발자를 위한 Python 중급

Jasmin Ludolf

Senior Data Science Content Developer

모듈이란?

  • 모듈 = Python 스크립트
    • .py로 끝나는 파일
    • 함수와 속성 포함
    • 다른 모듈을 포함할 수 있음

$$

$$

$$

  • 이미 있는 코드를 다시 쓸 필요가 없음

거울 속에 비친 여러 개의 자기 모습을 바라보는 남자

개발자를 위한 Python 중급

Python 모듈

  • os:
    • 운영 체제를 통해 작업을 처리하는 데 사용됨
    • 현재 디렉터리 확인
    • 사용 가능한 파일을 목록으로 표시
    • 환경 변수 접근
  • string:
    • 텍스트 처리 작업을 단순화

Python 모듈

개발자를 위한 Python 중급

모듈 가져오기

# General syntax
import <module_name>
# Import the os module
import os
# Check the type
print(type(os))
<class 'module'>
개발자를 위한 Python 중급

모듈의 함수 찾기

# Call help()
# Warning - will return a very large output!
print(help(os))
Help on module os:

NAME
    os - OS routines for NT or Posix depending on what system we're on.

MODULE REFERENCE
    https://docs.python.org/3.12/library/os.html
    ...
개발자를 위한 Python 중급

현재 작업 디렉터리 가져오기

# Using an os function
print(os.getcwd())
/home/courses/intermediate_python_for_developers

$$

  • 나중에 다시 디렉터리를 참조해야 할 경우 유용함
# Assign to a variable
work_dir = os.getcwd()
개발자를 위한 Python 중급

디렉터리 변경하기

# Changing directory
os.chdir("/home/courses")
# Check the current directory
print(os.getcwd())
/home/courses
# Confirm work_dir has not changed
print(work_dir)
/home/courses/intermediate_python_for_developers
개발자를 위한 Python 중급

모듈 속성

  • 속성은 값을 반환함
  • 함수는 작업을 수행함
  • 속성에는 괄호를 사용하지 않음
# Get the local environment
print(os.environ)
environ{'PATH': '/usr/local/bin',
        'TERM': 'xterm',
        'HOSTNAME': '097a0fe4-d6ce-4325-a6e2-1d0ce2800c2b',
        'TZ': 'Europe/Brussels',
        'LANG': 'en_US.UTF-8',
         ...
개발자를 위한 Python 중급

문자열 모듈

import string


print(string.ascii_lowercase)
abcdefghijklmnopqrstuvwxyz

$$

  • 문자열에 문자, 숫자 또는 특정 문자가 포함되어 있는지 확인함

$$

  • 사용자 입력 내용을 검증하는 데 유용함 💡
print(string.digits)
0123456789

$$

print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
개발자를 위한 Python 중급

연습해 봅시다!

개발자를 위한 Python 중급

Preparing Video For Download...