第10章文件和异常

10.1 文件中读取数据

10.1.1 读取整个文件

with open('files/pi_digist.txt') as file_object:
conent = file_object.read()
print(conent)
with:此关键字在不需要访问文件后将其关闭,也可不适用with手动调用关闭,但是需避免异常情况带来的问题;
open as:open返回一个文件对象,as 将文件对象存储在 变量中
read():读取整个文件

10.1.2 文件路径

若只传递文件名,会在当前执行文件所在目录中查找文件
可使用相对路径、绝对路径

10.1.3 逐行读取

with open('files/pi_digist.txt') as file_object:
for line in file_object:
print(line)  #每行末尾都有一个空行,因为每行末尾都有一个看不到的换行符,print方法自身带一个换行符,因此会有两个换行符;可使用line.rstrip()删除文本中的换行符

10.1.4 创建一个包含文件各行内容的列表

只能在with模块内能使用打开的文件对象,可将文件内各行存储在一个列表中,并在with代码块外使用该列表。
with open('files/pi_digist.txt') as file_object:
lines=file_object.readlines() #存储在列表中,可在with模块外部访问
for line in lines:
print(line) 

10.2 写入文件

with open('..\hello2.txt','a') as file_obj:
file_obj.write('hello write func!')
file_obj.write('hello write func2!')
open 方法:
第一个参数:路径
第二个参数:写入模式;r:只读;w:写入;r+:读写;a:附加(不会覆盖);默认只读;

10.3 异常

使用 try-except代码块

try:
print(3/0)
except ZeroDivisionError :
print('can not divide zero')
excpt FileNotFoundError
pass #跳过异常,什么都不做
else:
print('ok')
 

10.4 存储数据

json.dump() 存储
 nums=[1,2,3,4,5]
 with open('..\json.txt','w') as file_obj:
 json.dump(nums,file_obj)
 
json.load()读取
with open('..\json.txt','r') as file_obj:
nums=json.load(file_obj)
print(nums)
 
重构
代码能够正确的运行,但可做进一步的改进----将代码分为一系列完成具体工作的函数,这个过程叫重构。重构让代码更加清晰,易于理解,易于扩展
 
 
 
 
 
posted @ 2019-07-21 17:28  vvf  阅读(184)  评论(0编辑  收藏  举报