文件读写基础
- 使用
open()
函数打开文件,返回文件对象
- 模式参数:
r
读、
w
写(覆盖)、
a
追加、
b
二进制
- 读写完成后必须调用
close()
关闭文件
- 推荐用
with
语句自动管理资源关闭
f=
open('data.txt','r',encoding='utf-8')
text=f.
read()f.
close()
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)
文件读写完整示例
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)
异常处理基础
- 程序运行时发生的错误称为
异常(Exception)
- 不处理异常会导致程序崩溃并终止执行
- 使用
try/except
捕获并处理异常
-
finally
块中的代码无论是否异常都会执行
try:
x=
int(input("请输入一个数字:"))
result=100/x
print(f"结果是: {result} ")
exceptValueError:
print("输入无效,请输入数字")
exceptZeroDivisionError:
print("不能除以零")
finally:
print("程序执行完毕")
常见异常类型
内置异常
ValueError
— 值类型错误
TypeError
— 类型不匹配
IndexError
— 索引越界
KeyError
— 字典键不存在
IO 相关
FileNotFoundError
— 文件不存在
PermissionError
— 权限不足
IOError
— 输入输出错误
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
- 继承
Exception
类可自定义业务异常
- 使用
raise
主动抛出异常
- 用异常传递错误信息,比返回错误码更清晰
classValidationError(Exception):
"""参数验证失败时抛出"""
pass
defset_age(age):
ifnotisinstance(age,int)
orage<0:
raise
ValidationError("年龄必须是正整数")
returnage
try:
set_age(-5)
exceptValidationErrorase:
print(f"验证失败: {e} ")
模块导入
- 模块(Module)是一个包含 Python 代码的 .py 文件
- 包(Package)是包含
__init__.py
的文件夹
- 使用
import
导入模块,使用
from...import
导入指定内容
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 查看
defhello(name):
returnf"Hello, {name} !"
if__name__=="__main__":
print(hello("World"))
print(hello("Python"))