模块

Python 中级:面向开发者

Jasmin Ludolf

Senior Data Science Content Developer

什么是模块?

  • 模块是 Python 脚本
    • .py 结尾的文件
    • 包含函数和属性
    • 也可包含其他模块

$$

$$

$$

  • 帮助我们避免重复造轮子!

男子看向倒影,看到更多倒影

Python 中级:面向开发者

Python 模块

  • 约有 200 个内置模块
  • os
    • 与操作系统交互
    • 查看当前目录
    • 列出可用文件
    • 访问环境变量
  • string
    • 简化文本处理

Python 模块

Python 中级:面向开发者

导入模块

# 通用语法
import <module_name>
# 导入 os 模块
import os
# 检查类型
print(type(os))
<class 'module'>
Python 中级:面向开发者

查找模块的函数

# 调用 help()
# 警告:输出会非常长!
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 中级:面向开发者

获取当前工作目录

# 使用 os 函数
print(os.getcwd())
/home/courses/intermediate_python_for_developers

$$

  • 如需稍后引用该目录时很有用
# 赋值给变量
work_dir = os.getcwd()
Python 中级:面向开发者

更改目录

# 切换目录
os.chdir("/home/courses")
# 检查当前目录
print(os.getcwd())
/home/courses
# 确认 work_dir 未改变
print(work_dir)
/home/courses/intermediate_python_for_developers
Python 中级:面向开发者

模块属性

  • 属性返回值
  • 函数执行任务
  • 属性后不要加括号
# 获取本地环境
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 中级:面向开发者

string 模块

import string


print(string.ascii_lowercase)
abcdefghijklmnopqrstuvwxyz

$$

  • 检查字符串是否包含字母、数字或特定字符

$$

  • 适合校验用户输入 💡
print(string.digits)
0123456789

$$

print(string.punctuation)
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Python 中级:面向开发者

让我们来练习!

Python 中级:面向开发者

Preparing Video For Download...