长风破浪会有时,直挂云帆济沧海

Dream Word

博客园 首页 新随笔 联系 订阅 管理

chapter10 文件和异常
10.1 从文件中读取数据
10.1.1 读取整个文件
with open("pi.txt") as file_object:
contents = file_object.read()
print(contents)
print(contents.rstrip())//去掉空白行
10.1.2 文件路径
10.1.3 逐行读取
filename = 'pi.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
10.1.4 创建一个包含文件各行内容的列表
使用with关键字,open()返回的文件对象只在with代码块内可用。
filename = 'pi.txt'
with open(filename) as file_object:
lines = file_object.readlines()
for line in lines:
print(line.tstrip())
10.1.5 使用文件的内容
删除每行末尾的换行符 -> rstrip()
删除每行左边的空格 -> strip()
10.1.6 包含一百万位3的大型文件
filename = 'pi.txt'

with open(filename) as file_object():
lines = file_object.readlines()

pi_string =''
for line in lines:
pi_string += line.strip()

print(pi_string[:52] + "...")
print(len(pi_string))
10.1.7 圆周率值中包含你的升入吗
birthday = input("Enter your birthday,in the form mmddyy:")
if birthday in pi_string:
print("OK")
else:
print("No")
10.2 写入文件
10.2.1 写入空文件
filename = "programming.txt"

with open(filename,'w') as file_object:
file_object.write("I love programming")
10.2.2 写入多行
10.2.3 附加到文件
10.3 异常
10.3.1 处理ZeroDivisionError异常
10.3.2 使用try-except代码块
try:
print(5/0)
except ZeroDivisonError:
print("You can't divide by zero")
10.3.3 使用异常避免崩溃
10.3.4 else 代码块
try:
answer = int(first_number)/int(second_number)
exception ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
10.3.5 处理FileNoFoundError异常
filename = "alice.txt"

try:
with open(filename) as f_obj:
contents = f_obj.read()
excep FileNotFoundError:
msg = "Sorry, the file " + filename + " does not exit"
print(msg)
10.3.6 分析文本
split() //根据空格分割字符串到列表
10.3.7 使用多个文件
10.3.8 失败时一声不吭
try:
//...
catch FileNotFoundError:
pass
else:
--snip--
10.4 存储数据
10.4.1 使用json.dump()和json.load()
//保存到文件
import json

numbers = [2,3,4,5,6,6]

filename = 'numbers.json'
with open(filename,'w') as file_object:
json.dump(numbers,file_object)

//读取到内存
import json

filename = 'numbers.json'
with open(filename) as file_object:
numbers = json.load(file_object)
print(numbers)
10.4.2 保存和读取用户生成的数据
10.4.3 重构

 

posted on 2017-12-24 23:24  长风II  阅读(221)  评论(0编辑  收藏  举报