Python 基础:常用内置库
7.1 os - 操作系统接口
python
import os
os.getcwd() # 当前工作目录
os.chdir("/path/to/dir") # 切换目录
os.listdir(".") # 列出目录内容
os.mkdir("new_dir") # 创建目录
os.makedirs("a/b/c") # 递归创建目录
os.remove("file.txt") # 删除文件
os.rmdir("empty_dir") # 删除空目录
os.path.exists("file.txt") # 文件是否存在
os.path.join("dir", "file") # 拼接路径1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
7.2 sys - 系统相关
python
import sys
sys.argv # 命令行参数列表
sys.version # Python 版本
sys.path # 模块搜索路径
sys.exit(0) # 退出程序1
2
3
4
5
6
2
3
4
5
6
7.3 datetime - 日期时间
python
from datetime import datetime, timedelta
now = datetime.now()
print(now) # 2024-01-15 10:30:45.123456
# 格式化
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2024-01-15 10:30:45
print(now.strftime("%B %d, %Y")) # January 15, 2024
# 解析
dt = datetime.strptime("2024-01-15", "%Y-%m-%d")
# 时间计算
tomorrow = now + timedelta(days=1)
yesterday = now - timedelta(days=1)1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
7.4 json - JSON 处理
python
import json
# Python → JSON 字符串
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data, ensure_ascii=False, indent=2)
# JSON 字符串 → Python
data2 = json.loads(json_str)1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
7.5 re - 正则表达式
python
import re
text = "我的手机号是 138-1234-5678"
pattern = r"1[3-9]\d{1}-\d{4}-\d{4}"
match = re.search(pattern, text)
if match:
print(match.group()) # 138-1234-5678
# 常用方法
re.findall(r"\d+", text) # 找到所有数字
re.sub(r"\d+", "XXX", text) # 替换数字为XXX
re.split(r"\D+", text) # 按非数字分割1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
7.6 collections - 容器类型
python
from collections import Counter, defaultdict, OrderedDict
# Counter 计数器
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
counter = Counter(words)
print(counter.most_common(2)) # [('apple', 3), ('banana', 2)]
# defaultdict 默认字典
d = defaultdict(list)
d["fruits"].append("apple")
print(d["fruits"]) # ["apple"]
# OrderedDict 有序字典(Python 3.7+ 普通 dict 已有序)1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
7.7 itertools - 迭代工具
python
import itertools
# count 无限计数器
for i in zip(range(5), itertools.count(10)):
print(i) # (0,10), (1,11), (2,12), (3,13), (4,14)
# cycle 循环
cycler = itertools.cycle(["A", "B", "C"])
for _ in range(5):
print(next(cycler)) # A, B, C, A, B
# chain 连接多个迭代器
combined = list(itertools.chain([1, 2], [3, 4]))
print(combined) # [1, 2, 3, 4]
# permutations 排列
print(list(itertools.permutations([1, 2, 3], 2)))
# [(1,2), (1,3), (2,1), (2,3), (3,1), (3,2)]
# combinations 组合
print(list(itertools.combinations([1, 2, 3], 2)))
# [(1,2), (1,3), (2,3)]1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[[返回 Python 首页|python/index]]