Python 基础

第八章 · 文件、异常和模块

配合机器学习系列课程

欢迎关注微信公众号

coder程 查令十街84号

本章目录

1. 文件读写

打开文件、读写模式、上下文管理器 with

2. 异常处理

try/except/finally、常见异常类型、自定义异常

3. 模块导入

import 语法、模块搜索路径、__name__ 机制

文件读写基础

# 基础写法(不推荐) f= open('data.txt','r',encoding='utf-8') text=f. read()f. close() # 推荐写法:with 上下文管理器 withopen('data.txt','r',encoding='utf-8')asf: text=f. read() # 自动关闭文件,即使发生异常

文件读写方法详解

读取方法

read() — 读取全部内容

readline() — 读取一行

readlines() — 读取为列表

for line in f — 逐行迭代

写入方法

write() — 写入字符串

writelines() — 写入列表

# 逐行读取大文件(推荐) withopen('big_file.txt','r') asf: forlineinf: print(line.strip()) # 写入多行 lines=['line1\n','line2\n','line3\n'] withopen('output.txt','w')asf: f. writelines(lines)

文件读写完整示例

# 读取 CSV 数据并计算平均值 defcalc_average(filename): total=0 count=0 withopen(filename,'r',encoding='utf-8')asf: forlineinf: line=line. strip() iflineandnotline. startswith('#'): total+= float(line) count+=1 returntotal/count ifcount>0 else0 # 复制二进制文件 withopen('source.jpg','rb') assrc: data=src. read() withopen('copy.jpg','wb') asdst:dst. write(data)

异常处理基础

try: x= int(input("请输入一个数字:")) result=100/x print(f"结果是: {result} ") exceptValueError: print("输入无效,请输入数字") exceptZeroDivisionError: print("不能除以零") finally: print("程序执行完毕")

常见异常类型

内置异常

ValueError — 值类型错误

TypeError — 类型不匹配

IndexError — 索引越界

KeyError — 字典键不存在

IO 相关

FileNotFoundError — 文件不存在

PermissionError — 权限不足

IOError — 输入输出错误

# 捕获多个异常 + else 子句 try: withopen('config.json','r') asf: data=json. load(f) except(FileNotFoundError,PermissionError) ase: print(f"文件访问失败: {e} ") exceptjson.JSONDecodeError: print("JSON 格式错误") else: print("读取成功!",data)

自定义异常与 raise

classValidationError(Exception): """参数验证失败时抛出""" pass defset_age(age): ifnotisinstance(age,int) orage<0: raise ValidationError("年龄必须是正整数") returnage try: set_age(-5) exceptValidationErrorase: print(f"验证失败: {e} ")

模块导入

# 导入整个模块 importmath print(math.sqrt(16)) # 导入模块中的特定函数 frommath importsqrt,pi print(sqrt(16),pi) # 给模块起别名 importnumpyasnp print(np.array([1,2,3])) # 导入所有内容(不推荐) frommath import*

__name__ 与模块搜索路径

__name__ 机制

直接运行模块时, __name__ == "__main__"

被导入时, __name__ == 模块名

用于编写可测试的模块

搜索路径

1. 当前目录

2. PYTHONPATH 环境变量

3. 标准库路径

用 sys.path 查看

# mymodule.py — 标准模块模板 defhello(name): returnf"Hello, {name} !" if__name__=="__main__": # 直接运行时的测试代码 print(hello("World")) print(hello("Python"))

本章总结

▸ 文件读写:open() + with 语句,掌握 r/w/a/b 四种模式

▸ 异常处理:try/except/finally,精准捕获,优雅降级

▸ 模块导入:import / from...import,理解 __name__ 机制

▸ 好习惯:用 with 管理资源,自定义异常提升代码质量

下一章 ▶