模組

Intermediate Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

什麼是模組?

  • 模組是 Python 指令碼
    • .py 結尾的檔案
    • 內含函式與屬性
    • 也可包含其他模組

$$

$$

$$

  • 幫助你避免重寫現有程式碼!

男子看著倒影,映出更多倒影

Intermediate Python for Developers

Python 模組

  • 內建模組約有 200 個
  • os
    • 用於與作業系統互動
    • 檢查目前目錄
    • 列出可用檔案
    • 存取環境變數
  • string
    • 簡化文字處理工作

Python 模組

Intermediate Python for Developers

匯入模組

# General syntax
import <module_name>
# Import the os module
import os
# Check the type
print(type(os))
<class 'module'>
Intermediate Python for Developers

尋找模組的函式

# 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
    ...
Intermediate Python for Developers

取得目前工作目錄

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

$$

  • 若之後需要引用目錄,這很實用
# Assign to a variable
work_dir = os.getcwd()
Intermediate Python for Developers

切換目錄

# 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
Intermediate Python for Developers

模組屬性

  • 屬性會回傳值
  • 函式用來執行任務
  • 屬性不用加括號
# 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',
         ...
Intermediate Python for Developers

String 模組

import string


print(string.ascii_lowercase)
abcdefghijklmnopqrstuvwxyz

$$

  • 檢查字串是否含有英文字母、數字或特定符號

$$

  • 驗證使用者輸入很方便 💡
print(string.digits)
0123456789

$$

print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Intermediate Python for Developers

一起來練習吧!

Intermediate Python for Developers

Preparing Video For Download...