第01章 Python基础核心

1.1 Python环境与解释器

1.1.1 Python安装

Python支持多平台安装,包括Windows、macOS和Linux。推荐从官方网站下载最新稳定版本。

Windows安装步骤:

  1. 访问 https://www.python.org/downloads/windows/
  2. 下载对应版本的安装包
  3. 运行安装程序,勾选"Add Python to PATH"

macOS安装步骤:

# 使用Homebrew安装
brew install python3

Linux安装步骤:

# Ubuntu/Debian
sudo apt update && sudo apt install python3 python3-pip

# CentOS/RHEL
sudo yum install python3 python3-pip

1.1.2 虚拟环境venv

虚拟环境可以隔离项目依赖,避免版本冲突。

创建虚拟环境:

# 创建虚拟环境
python -m venv myenv

# 激活虚拟环境
# Windows
myenv\Scripts\activate
# macOS/Linux
source myenv/bin/activate

案例1:虚拟环境管理脚本

import os
import subprocess
import sys

def create_venv(env_name: str = "venv") -> None:
    """创建虚拟环境"""
    subprocess.run([sys.executable, "-m", "venv", env_name], check=True)
    print(f"虚拟环境 {env_name} 创建成功")

def activate_venv(env_name: str = "venv") -> None:
    """激活虚拟环境(显示命令)"""
    if os.name == "nt":
        activate_cmd = f"{env_name}\\Scripts\\activate"
    else:
        activate_cmd = f"source {env_name}/bin/activate"
    print(f"运行以下命令激活虚拟环境:\n{activate_cmd}")

if __name__ == "__main__":
    create_venv()
    activate_venv()

1.1.3 pip包管理

pip是Python的包管理工具,用于安装和管理第三方库。

常用pip命令:

# 安装包
pip install requests

# 指定版本安装
pip install requests==2.31.0

# 升级包
pip install --upgrade requests

# 卸载包
pip uninstall requests

# 导出依赖
pip freeze > requirements.txt

# 安装依赖
pip install -r requirements.txt

案例2:依赖管理工具

import subprocess
import sys

def install_requirements(filepath: str = "requirements.txt") -> None:
    """从requirements.txt安装依赖"""
    subprocess.run([sys.executable, "-m", "pip", "install", "-r", filepath], check=True)

def export_requirements(filepath: str = "requirements.txt") -> None:
    """导出当前环境依赖"""
    result = subprocess.run([sys.executable, "-m", "pip", "freeze"], 
                          capture_output=True, text=True)
    with open(filepath, "w") as f:
        f.write(result.stdout)
    print(f"依赖已导出到 {filepath}")

if __name__ == "__main__":
    export_requirements()

1.2 数据类型详解

1.2.1 数值类型(int/float)

int类型方法:

# 进制转换
num = 42
print(bin(num))   # 二进制: 0b101010
print(oct(num))   # 八进制: 0o52
print(hex(num))   # 十六进制: 0x2a

# 绝对值和比较
print(abs(-42))   # 42
print(pow(2, 10)) # 1024

float类型方法:

pi = 3.14159
print(round(pi, 2))      # 3.14
print(pi.as_integer_ratio())  # (3537115888337719, 1125899906842624)
print(pi.is_integer())   # False

案例3:数值计算工具

def calculate_statistics(numbers: list[float]) -> dict:
    """计算数值列表的统计信息"""
    if not numbers:
        return {}
    
    return {
        "sum": sum(numbers),
        "average": sum(numbers) / len(numbers),
        "min": min(numbers),
        "max": max(numbers),
        "count": len(numbers)
    }

if __name__ == "__main__":
    data = [1.5, 2.3, 4.7, 3.2, 5.1]
    stats = calculate_statistics(data)
    print(stats)
    # 输出: {'sum': 16.8, 'average': 3.36, 'min': 1.5, 'max': 5.1, 'count': 5}

1.2.2 字符串类型(str)

常用字符串方法:

s = "Hello, Python!"

# 基本操作
print(s.upper())       # HELLO, PYTHON!
print(s.lower())       # hello, python!
print(s.strip())       # 去除首尾空格

# 查找和替换
print(s.find("Python"))  # 7
print(s.replace("Python", "World"))  # Hello, World!

# 分割和连接
print(s.split(", "))   # ['Hello', 'Python!']
print("-".join(["a", "b", "c"]))  # a-b-c

# 格式化
name = "Alice"
age = 30
print(f"My name is {name}, I'm {age} years old.")

案例4:字符串处理工具

def process_string(text: str) -> dict:
    """处理字符串并返回统计信息"""
    words = text.split()
    
    return {
        "length": len(text),
        "word_count": len(words),
        "upper_count": sum(1 for c in text if c.isupper()),
        "lower_count": sum(1 for c in text if c.islower()),
        "digit_count": sum(1 for c in text if c.isdigit()),
        "palindrome": text == text[::-1]
    }

if __name__ == "__main__":
    result = process_string("Hello World 2024")
    print(result)

1.2.3 列表类型(list)

常用列表方法:

fruits = ["apple", "banana", "cherry"]

# 添加元素
fruits.append("date")           # 末尾添加
fruits.insert(1, "blueberry")   # 指定位置插入

# 删除元素
fruits.remove("banana")         # 按值删除
popped = fruits.pop()           # 弹出末尾元素
del fruits[0]                   # 按索引删除

# 排序和反转
nums = [3, 1, 4, 1, 5, 9]
nums.sort()                     # 原地排序
nums.reverse()                  # 原地反转

案例5:列表操作综合示例

def manage_list(items: list) -> list:
    """演示列表的各种操作"""
    # 创建副本
    original = items.copy()
    
    # 添加元素
    items.append("new_item")
    
    # 切片操作
    middle = items[1:-1]
    
    # 列表推导式
    squared = [x**2 for x in [1, 2, 3, 4, 5]]
    
    return {"original": original, "modified": items, "middle": middle, "squared": squared}

if __name__ == "__main__":
    result = manage_list(["a", "b", "c", "d"])
    print(result)

1.2.4 元组类型(tuple)

元组是不可变的序列类型,适合存储不应该被修改的数据。

元组特点:

point = (3, 4)
x, y = point          # 解包
print(f"坐标: ({x}, {y})")

# 元组可以包含不同类型
person = ("Alice", 30, True)

# 元组作为字典键
locations = {
    (39.9042, 116.4074): "Beijing",
    (31.2304, 121.4737): "Shanghai"
}

1.2.5 字典类型(dict)

常用字典方法:

student = {
    "name": "Alice",
    "age": 20,
    "grades": {"math": 95, "english": 88}
}

# 访问值
print(student["name"])          # Alice
print(student.get("age"))       # 20
print(student.get("address", "Unknown"))  # Unknown

# 修改值
student["age"] = 21
student["grades"]["math"] = 97

# 遍历字典
for key, value in student.items():
    print(f"{key}: {value}")

案例6:字典操作工具

def merge_dicts(*dicts: dict) -> dict:
    """合并多个字典"""
    result = {}
    for d in dicts:
        result.update(d)
    return result

def deep_get(data: dict, path: str, default=None):
    """安全获取嵌套字典的值"""
    keys = path.split(".")
    current = data
    for key in keys:
        if isinstance(current, dict) and key in current:
            current = current[key]
        else:
            return default
    return current

if __name__ == "__main__":
    config = {"database": {"host": "localhost", "port": 5432}}
    print(deep_get(config, "database.host"))  # localhost
    print(deep_get(config, "database.password", "secret"))  # secret

1.2.6 集合类型(set)

集合是无序的不重复元素集合,支持数学集合操作。

常用集合操作:

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

# 集合操作
print(a | b)  # 并集: {1, 2, 3, 4, 5, 6}
print(a & b)  # 交集: {3, 4}
print(a - b)  # 差集: {1, 2}
print(a ^ b)  # 对称差: {1, 2, 5, 6}

# 添加和删除
a.add(5)
a.remove(1)  # 不存在会报错
a.discard(10)  # 不存在不会报错

案例7:集合应用示例

def find_duplicates(items: list) -> set:
    """找出列表中的重复元素"""
    seen = set()
    duplicates = set()
    for item in items:
        if item in seen:
            duplicates.add(item)
        seen.add(item)
    return duplicates

def unique_items(items: list) -> list:
    """返回列表中的唯一元素(保持顺序)"""
    seen = set()
    result = []
    for item in items:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

if __name__ == "__main__":
    data = [1, 2, 2, 3, 3, 3, 4, 5]
    print(find_duplicates(data))  # {2, 3}
    print(unique_items(data))     # [1, 2, 3, 4, 5]

1.3 控制流

1.3.1 if语句

基本语法:

age = 18
if age < 18:
    print("未成年")
elif age >= 18 and age < 65:
    print("成年人")
else:
    print("老年人")

案例8:成绩等级判断

def get_grade(score: int) -> str:
    """根据分数返回等级"""
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

if __name__ == "__main__":
    print(get_grade(85))  # B

1.3.2 for循环

遍历列表:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# 带索引遍历
for i, fruit in enumerate(fruits):
    print(f"{i+1}. {fruit}")

案例9:遍历字典并格式化输出

def print_dict(d: dict) -> None:
    """格式化打印字典内容"""
    for key, value in d.items():
        print(f"{key}: {value}")

if __name__ == "__main__":
    person = {"name": "Alice", "age": 30, "city": "Beijing"}
    print_dict(person)

1.3.3 while循环

基本语法:

count = 0
while count < 5:
    print(count)
    count += 1

案例10:猜数字游戏

import random

def guess_number() -> None:
    """简单的猜数字游戏"""
    target = random.randint(1, 100)
    guess = 0
    
    while guess != target:
        guess = int(input("猜一个1-100的数字: "))
        if guess < target:
            print("太小了!")
        elif guess > target:
            print("太大了!")
    
    print(f"恭喜!你猜对了,答案是 {target}")

if __name__ == "__main__":
    guess_number()

1.3.4 match-case语句(Python 3.10+)

基本语法:

status = "success"

match status:
    case "success":
        print("操作成功")
    case "error":
        print("操作失败")
    case _:
        print("未知状态")

案例11:HTTP状态码处理

def handle_status(code: int) -> str:
    """根据HTTP状态码返回描述"""
    match code:
        case 200:
            return "成功"
        case 301 | 302:
            return "重定向"
        case 400:
            return "请求错误"
        case 401:
            return "未授权"
        case 403:
            return "禁止访问"
        case 404:
            return "资源未找到"
        case 500:
            return "服务器错误"
        case _:
            return f"未知状态码: {code}"

if __name__ == "__main__":
    print(handle_status(404))  # 资源未找到

1.3.5 列表推导式

基本语法:

# 生成平方数列表
squares = [x**2 for x in range(10)]
print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# 带条件过滤
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

案例12:列表推导式实战

def process_data(data: list[int]) -> dict:
    """使用列表推导式处理数据"""
    positives = [x for x in data if x > 0]
    negatives = [x for x in data if x < 0]
    evens = [x for x in data if x % 2 == 0]
    
    return {
        "positives": positives,
        "negatives": negatives,
        "evens": evens,
        "squared": [x**2 for x in data],
        "abs_values": [abs(x) for x in data]
    }

if __name__ == "__main__":
    result = process_data([-3, -2, -1, 0, 1, 2, 3])
    print(result)

1.3.6 生成器表达式

基本语法:

# 生成器表达式(节省内存)
gen = (x**2 for x in range(10))
print(gen)  # <generator object <genexpr> at 0x...>

# 转换为列表
print(list(gen))  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

案例13:生成器表达式应用

def fibonacci(n: int):
    """生成斐波那契数列"""
    a, b = 0, 1
    for _ in range(n):
        yield a
        a, b = b, a + b

if __name__ == "__main__":
    # 使用生成器
    for num in fibonacci(10):
        print(num, end=" ")  # 0 1 1 2 3 5 8 13 21 34

1.4 函数与参数

1.4.1 函数定义

基本语法:

def greet(name: str) -> str:
    """返回问候语"""
    return f"Hello, {name}!"

print(greet("Alice"))  # Hello, Alice!

案例14:数学函数集合

def calculate_area(shape: str, **kwargs) -> float:
    """计算不同形状的面积"""
    match shape:
        case "circle":
            return 3.14159 * kwargs["radius"] ** 2
        case "rectangle":
            return kwargs["width"] * kwargs["height"]
        case "triangle":
            return kwargs["base"] * kwargs["height"] / 2
        case _:
            raise ValueError(f"未知形状: {shape}")

if __name__ == "__main__":
    print(calculate_area("circle", radius=5))  # 78.53975

1.4.2 参数类型

位置参数:

def add(a: int, b: int) -> int:
    return a + b

result = add(3, 5)  # 位置参数

关键字参数:

def introduce(name: str, age: int, city: str) -> str:
    return f"{name} is {age} years old, from {city}"

print(introduce(name="Alice", age=30, city="Beijing"))

默认参数:

def power(base: int, exponent: int = 2) -> int:
    return base ** exponent

print(power(3))      # 9 (使用默认指数)
print(power(3, 3))   # 27

可变参数:

def sum_all(*args: int) -> int:
    """接受任意数量的位置参数"""
    return sum(args)

print(sum_all(1, 2, 3, 4))  # 10

def print_info(**kwargs: str) -> None:
    """接受任意数量的关键字参数"""
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age="30", city="Beijing")

1.4.3 类型注解

函数类型注解:

def process_items(items: list[str]) -> tuple[list[str], int]:
    """处理字符串列表"""
    cleaned = [item.strip() for item in items]
    return cleaned, len(cleaned)

result = process_items(["  apple ", " banana ", "cherry"])
print(result)  # (['apple', 'banana', 'cherry'], 3)

1.4.4 闭包

闭包示例:

def make_counter():
    """创建计数器函数"""
    count = 0
    
    def counter():
        nonlocal count
        count += 1
        return count
    
    return counter

# 使用闭包
counter1 = make_counter()
print(counter1())  # 1
print(counter1())  # 2

counter2 = make_counter()
print(counter2())  # 1

案例15:闭包应用 - 配置化函数

def make_formatter(prefix: str, suffix: str):
    """创建带前后缀的格式化函数"""
    def formatter(text: str) -> str:
        return f"{prefix}{text}{suffix}"
    return formatter

if __name__ == "__main__":
    html_tag = make_formatter("<p>", "</p>")
    print(html_tag("Hello"))  # <p>Hello</p>
    
    json_key = make_formatter('"', '":')
    print(json_key("name"))   # "name":

1.5 面向对象编程

1.5.1 类定义

基本语法:

class Person:
    """人类定义"""
    
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age
    
    def introduce(self) -> str:
        return f"My name is {self.name}, I'm {self.age} years old."

# 创建实例
person = Person("Alice", 30)
print(person.introduce())  # My name is Alice, I'm 30 years old.

1.5.2 继承

继承示例:

class Student(Person):
    """学生类(继承Person)"""
    
    def __init__(self, name: str, age: int, student_id: str):
        super().__init__(name, age)
        self.student_id = student_id
    
    def study(self, subject: str) -> str:
        return f"{self.name} is studying {subject}."

student = Student("Bob", 20, "S2024001")
print(student.introduce())  # My name is Bob, I'm 20 years old.
print(student.study("Math"))  # Bob is studying Math.

1.5.3 多态

多态示例:

class Dog:
    def speak(self) -> str:
        return "Woof!"

class Cat:
    def speak(self) -> str:
        return "Meow!"

class Bird:
    def speak(self) -> str:
        return "Tweet!"

def make_speak(animal):
    """接受任何实现了speak方法的对象"""
    print(animal.speak())

# 多态演示
make_speak(Dog())   # Woof!
make_speak(Cat())   # Meow!
make_speak(Bird())  # Tweet!

1.5.4 魔术方法

常用魔术方法:

class Vector:
    def __init__(self, x: float, y: float):
        self.x = x
        self.y = y
    
    def __add__(self, other: "Vector") -> "Vector":
        """向量加法"""
        return Vector(self.x + other.x, self.y + other.y)
    
    def __str__(self) -> str:
        """字符串表示"""
        return f"Vector({self.x}, {self.y})"
    
    def __len__(self) -> int:
        """返回维度"""
        return 2

v1 = Vector(3, 4)
v2 = Vector(1, 2)
v3 = v1 + v2
print(v3)      # Vector(4, 6)
print(len(v3)) # 2

1.5.5 property装饰器

property示例:

class Circle:
    def __init__(self, radius: float):
        self._radius = radius
    
    @property
    def radius(self) -> float:
        return self._radius
    
    @radius.setter
    def radius(self, value: float) -> None:
        if value <= 0:
            raise ValueError("半径必须大于0")
        self._radius = value
    
    @property
    def area(self) -> float:
        """计算面积(只读属性)"""
        return 3.14159 * self._radius ** 2

circle = Circle(5)
print(circle.radius)  # 5
print(circle.area)    # 78.53975
circle.radius = 10
print(circle.area)    # 314.159

1.5.6 dataclass(Python 3.7+)

dataclass示例:

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0  # 默认值
    
    def distance_to_origin(self) -> float:
        return (self.x**2 + self.y**2 + self.z**2) ** 0.5

# 创建实例
p1 = Point(3, 4)
p2 = Point(1, 2, 3)

print(p1)  # Point(x=3, y=4, z=0.0)
print(p1.distance_to_origin())  # 5.0

案例16:图书管理系统类设计

from dataclasses import dataclass
from typing import List

@dataclass
class Book:
    """图书类"""
    isbn: str
    title: str
    author: str
    year: int
    available: bool = True

class Library:
    """图书馆类"""
    
    def __init__(self):
        self.books: List[Book] = []
    
    def add_book(self, book: Book) -> None:
        self.books.append(book)
    
    def find_books_by_author(self, author: str) -> List[Book]:
        return [b for b in self.books if b.author == author]
    
    def borrow_book(self, isbn: str) -> bool:
        for book in self.books:
            if book.isbn == isbn and book.available:
                book.available = False
                return True
        return False

if __name__ == "__main__":
    library = Library()
    library.add_book(Book("978-7-111-53069-0", "Python编程", "Guido", 2020))
    library.add_book(Book("978-7-115-42857-7", "深入理解Python", "Luciano", 2018))
    
    print(library.find_books_by_author("Guido"))
    print(library.borrow_book("978-7-111-53069-0"))

1.6 异常处理

1.6.1 try-except语句

基本语法:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"除零错误: {e}")

多个异常处理:

try:
    data = {"key": "value"}
    print(data["nonexistent"])
except KeyError as e:
    print(f"键不存在: {e}")
except Exception as e:
    print(f"其他错误: {e}")

1.6.2 finally子句

finally示例:

file = None
try:
    file = open("example.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("文件不存在")
finally:
    if file:
        file.close()
        print("文件已关闭")

1.6.3 自定义异常

自定义异常示例:

class InvalidInputError(Exception):
    """自定义输入错误异常"""
    pass

def validate_input(value: int) -> None:
    if value < 0:
        raise InvalidInputError("输入值不能为负数")

try:
    validate_input(-1)
except InvalidInputError as e:
    print(f"错误: {e}")

1.6.4 异常链

异常链示例:

try:
    try:
        result = 10 / 0
    except ZeroDivisionError as e:
        raise ValueError("计算失败") from e
except ValueError as e:
    print(f"错误: {e}")
    print(f"原始错误: {e.__cause__}")

案例17:异常处理综合示例

def safe_divide(a: float, b: float) -> float:
    """安全除法,处理多种异常"""
    try:
        if not isinstance(a, (int, float)) or not isinstance(b, (int, float)):
            raise TypeError("参数必须是数字类型")
        if b == 0:
            raise ZeroDivisionError("除数不能为零")
        return a / b
    except (TypeError, ZeroDivisionError) as e:
        print(f"计算错误: {e}")
        return None

def process_numbers(numbers: list) -> list:
    """处理数字列表,跳过无效项"""
    results = []
    for num in numbers:
        try:
            results.append(float(num))
        except (ValueError, TypeError) as e:
            print(f"跳过无效值 '{num}': {e}")
    return results

if __name__ == "__main__":
    print(safe_divide(10, 2))   # 5.0
    print(safe_divide(10, 0))   # None
    print(process_numbers([1, "2", "abc", 3.5, None]))  # [1.0, 2.0, 3.5]

1.7 模块与包

1.7.1 import机制

基本导入:

import math
print(math.sqrt(16))  # 4.0

from math import pi, sqrt
print(pi)      # 3.141592653589793
print(sqrt(9)) # 3.0

from math import *
print(sin(0))  # 0.0

别名导入:

import numpy as np
import pandas as pd

arr = np.array([1, 2, 3])
df = pd.DataFrame({"a": [1, 2], "b": [3, 4]})

1.7.2 init.py

__init__.py 文件用于标识一个目录为Python包,并可以包含包的初始化代码。

示例结构:

mypackage/
├── __init__.py
├── module1.py
└── module2.py

init.py内容:

# 导出公共API
from .module1 import func1, func2
from .module2 import Class1, Class2

__all__ = ["func1", "func2", "Class1", "Class2"]
__version__ = "1.0.0"

1.7.3 相对导入

相对导入示例:

# 在mypackage/module1.py中
from . import module2          # 同包内导入
from .module2 import Class1    # 导入特定对象
from .. import utils           # 上级包导入

1.7.4 命名空间

命名空间示例:

# 全局命名空间
global_var = "global"

def func():
    # 局部命名空间
    local_var = "local"
    print(locals())

func()
print(globals())

案例18:模块导入演示

# 创建一个简单的模块结构
"""
utils/
├── __init__.py
├── math_utils.py
└── string_utils.py
"""

# math_utils.py
def add(a: int, b: int) -> int:
    return a + b

def multiply(a: int, b: int) -> int:
    return a * b

# string_utils.py
def reverse_string(s: str) -> str:
    return s[::-1]

def capitalize_words(s: str) -> str:
    return ' '.join(word.capitalize() for word in s.split())

# __init__.py
from .math_utils import add, multiply
from .string_utils import reverse_string, capitalize_words

# 使用模块
from utils import add, reverse_string
print(add(3, 5))           # 8
print(reverse_string("hello"))  # olleh

1.8 文件操作

1.8.1 open函数参数详解

基本语法:

file = open("example.txt", mode="r", encoding="utf-8")
content = file.read()
file.close()

mode参数说明:

  • r: 只读模式(默认)
  • w: 写入模式,覆盖文件
  • a: 追加模式
  • x: 独占创建模式
  • b: 二进制模式
  • t: 文本模式(默认)

常用组合:

  • rb: 二进制只读
  • wb: 二进制写入
  • r+: 读写模式
  • w+: 读写模式(创建新文件)

1.8.2 with语句

with语句自动管理文件:

with open("example.txt", "r", encoding="utf-8") as file:
    content = file.read()
    print(content)
# 文件自动关闭

1.8.3 pathlib模块

pathlib示例:

from pathlib import Path

# 创建路径对象
path = Path("docs")

# 检查路径
print(path.exists())    # True/False
print(path.is_dir())    # True/False
print(path.is_file())   # True/False

# 创建目录
path.mkdir(parents=True, exist_ok=True)

# 遍历目录
for file in path.glob("*.md"):
    print(file)

# 获取文件信息
file = Path("example.txt")
print(file.stat())      # 文件状态
print(file.suffix)      # .txt
print(file.stem)        # example

案例19:文件操作工具

from pathlib import Path

def read_file(filepath: str) -> str:
    """读取文件内容"""
    path = Path(filepath)
    if not path.exists():
        raise FileNotFoundError(f"文件不存在: {filepath}")
    return path.read_text(encoding="utf-8")

def write_file(filepath: str, content: str) -> None:
    """写入文件内容"""
    path = Path(filepath)
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content, encoding="utf-8")

def copy_file(source: str, destination: str) -> None:
    """复制文件"""
    source_path = Path(source)
    dest_path = Path(destination)
    dest_path.write_bytes(source_path.read_bytes())

if __name__ == "__main__":
    write_file("output/hello.txt", "Hello, World!")
    content = read_file("output/hello.txt")
    print(content)  # Hello, World!

1.8.4 JSON读写

JSON操作示例:

import json

# 写入JSON
data = {"name": "Alice", "age": 30, "hobbies": ["reading", "coding"]}
with open("data.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=4)

# 读取JSON
with open("data.json", "r", encoding="utf-8") as f:
    loaded_data = json.load(f)
    print(loaded_data)  # {'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'coding']}

1.8.5 CSV读写

CSV操作示例:

import csv

# 写入CSV
data = [
    ["name", "age", "city"],
    ["Alice", 30, "Beijing"],
    ["Bob", 25, "Shanghai"],
    ["Charlie", 35, "Guangzhou"]
]
with open("data.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerows(data)

# 读取CSV
with open("data.csv", "r", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)

1.8.6 YAML读写

YAML操作示例:

# 需要安装pyyaml
# pip install pyyaml

import yaml

# 写入YAML
data = {
    "database": {
        "host": "localhost",
        "port": 5432,
        "credentials": {
            "username": "admin",
            "password": "secret"
        }
    }
}
with open("config.yaml", "w", encoding="utf-8") as f:
    yaml.dump(data, f, default_flow_style=False)

# 读取YAML
with open("config.yaml", "r", encoding="utf-8") as f:
    config = yaml.safe_load(f)
    print(config["database"]["host"])  # localhost

案例20:配置文件管理器

import json
import yaml
from pathlib import Path
from typing import Dict, Any

class ConfigManager:
    """配置文件管理器"""
    
    def __init__(self, config_dir: str = "config"):
        self.config_dir = Path(config_dir)
        self.config_dir.mkdir(parents=True, exist_ok=True)
    
    def load_json(self, filename: str) -> Dict[str, Any]:
        """加载JSON配置文件"""
        path = self.config_dir / filename
        if not path.exists():
            return {}
        with open(path, "r", encoding="utf-8") as f:
            return json.load(f)
    
    def save_json(self, filename: str, data: Dict[str, Any]) -> None:
        """保存JSON配置文件"""
        path = self.config_dir / filename
        with open(path, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=4)
    
    def load_yaml(self, filename: str) -> Dict[str, Any]:
        """加载YAML配置文件"""
        path = self.config_dir / filename
        if not path.exists():
            return {}
        with open(path, "r", encoding="utf-8") as f:
            return yaml.safe_load(f)
    
    def save_yaml(self, filename: str, data: Dict[str, Any]) -> None:
        """保存YAML配置文件"""
        path = self.config_dir / filename
        with open(path, "w", encoding="utf-8") as f:
            yaml.dump(data, f, default_flow_style=False)

if __name__ == "__main__":
    manager = ConfigManager()
    
    # 保存配置
    manager.save_json("app.json", {"debug": True, "port": 8000})
    manager.save_yaml("database.yaml", {"host": "localhost", "port": 5432})
    
    # 加载配置
    app_config = manager.load_json("app.json")
    db_config = manager.load_yaml("database.yaml")
    print(app_config)   # {'debug': True, 'port': 8000}
    print(db_config)    # {'host': 'localhost', 'port': 5432}

小结

本章介绍了Python基础核心知识,包括:

  1. Python环境与解释器管理
  2. 六大数据类型详解及操作方法
  3. 控制流语句(if/for/while/match-case)
  4. 函数定义与参数类型
  5. 面向对象编程(类、继承、多态、魔术方法)
  6. 异常处理机制
  7. 模块与包的导入和命名空间
  8. 文件操作(open、pathlib、JSON/CSV/YAML)

这些基础知识是学习Python高级特性和后续章节的基础。

更多推荐