前言
Python 有一句话叫 batteries included,大概意思是标准库自带很多常用能力。
初学时不需要马上追一堆第三方库。很多日常脚本用标准库就能完成。比如处理路径、时间、JSON、CSV、命令行参数、日志、随机数、HTTP 简单请求等。
这篇记录几个我觉得初学阶段最值得先熟悉的标准库。不是完整教程,而是知道它们能解决什么问题。
pathlib
pathlib 用来处理文件路径。
from pathlib import Path
base_dir = Path("data")
file_path = base_dir / "users.txt"
它比字符串拼接路径更清楚。
常用操作:
file_path.exists()
file_path.name
file_path.suffix
file_path.parent
遍历目录:
for path in Path("data").glob("*.txt"):
print(path)
写脚本处理文件时,pathlib 基本必学。
datetime
datetime 用来处理日期时间。
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
格式化:
text = now.strftime("%Y-%m-%d %H:%M:%S")
解析字符串:
dt = datetime.strptime("04-16", "%m-%d")
初学时要注意日期格式里的大小写。%m是月份,%M是分钟。这个很容易写错。
json
json 用来处理 JSON 数据。
import json
data = {"name": "Tom", "age": 18}
text = json.dumps(data, ensure_ascii=False)
字符串转对象:
data = json.loads(text)
文件读写:
with open("data.json", "w", encoding="utf-8") as file:
json.dump(data, file, ensure_ascii=False, indent=2)
处理接口响应、配置文件、小数据存储时都很常用。
csv
csv 用来读写表格类文本文件。
读取:
import csv
with open("users.csv", "r", encoding="utf-8") as file:
reader = csv.DictReader(file)
for row in reader:
print(row["name"])
写入:
with open("users.csv", "w", encoding="utf-8", newline="") as file:
writer = csv.DictWriter(file, fieldnames=["name", "age"])
writer.writeheader()
writer.writerow({"name": "Tom", "age": 18})
newline=""在写 CSV 时建议加上,避免某些系统里出现空行问题。
如果只是简单处理 CSV,标准库够用。复杂数据分析再考虑 pandas。
argparse
argparse 用来写命令行参数。
比如你写了一个处理文件的脚本,不想把路径写死在代码里,就可以用 argparse。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--input", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
print(args.input)
运行:
python tool.py --input a.txt --output b.txt
这样脚本就更像一个小工具,而不是一次性代码。
logging
刚开始写 Python,很多人都用 print 调试。
print 没问题,但稍微正式一点的脚本,logging 更合适。
import logging
logging.basicConfig(level=logging.INFO)
logging.info("start")
logging.warning("something wrong")
logging 可以区分级别,也能配置输出格式和文件。
简单脚本可以先用 basicConfig,等项目复杂了再单独配置 logger。
不要所有信息都 print。日志级别能让运行信息更清楚。
random
random 用来生成随机数。
import random
number = random.randint(1, 10)
item = random.choice(["A", "B", "C"])
打乱列表:
items = [1, 2, 3]
random.shuffle(items)
它适合普通随机场景,比如测试数据、小游戏、抽样。安全相关随机不要用 random,要用 secrets。
collections
collections 里有一些很好用的数据结构。
Counter 可以计数:
from collections import Counter
words = ["java", "python", "python"]
counter = Counter(words)
print(counter)
defaultdict 可以给字典默认值:
from collections import defaultdict
groups = defaultdict(list)
groups["A"].append("Tom")
这些工具能让代码少写很多判断。
小结
Python 标准库很丰富,初学阶段不用一口气全学。
我觉得可以先熟悉 pathlib、datetime、json、csv、argparse、logging、random、collections。这几个覆盖了路径、时间、数据格式、命令行、日志和常用数据处理。
学标准库的目的不是背 API,而是知道遇到问题时先去哪里找工具。很多小需求不用装第三方包,标准库已经够用了。
喜欢的话,留下你的评论吧~