《head first python》——文件与异常
来源:互联网 发布:淘宝全球购认证商家 编辑:程序博客网 时间:2024/06/05 11:14
1. 查看当前路径,转到工作目录
>>> import os>>> os.getcwd()'C:\\Python27'>>> os.chdir("F:/data")>>> os.getcwd()'F:\\data'2. 数据切分,并赋值
>>> str = "hello:my name is: Anna">>> (say,words,name) = str.split(":")>>> words'my name is'注意分割次数
>>> (words,name) = str.split(":")Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> (words,name) = str.split(":")ValueError: too many values to unpack>>> (words,name) = str.split(":",1)>>> name'my name is: Anna'注意:在这里,返回值包含在一对小括号中间,称作元组,元组是不可改变的列表。
3. 异常捕获机制,try-except机制可以让你专注于代码真正需要做的工作,避免不必要的代码逻辑
程序运行过程中出现异常可能导致程序崩溃,通过try/except允许在异常发生时捕获异常,如果发现有问题,会执行你预先设定的恢复代码,然后继续执行程序。也就是在不崩溃的情况下系统地处理错误和异常。
首先是要找出容易出错、要保护的代码。
>>> try:data = fdtry:data1 = fd1except:passfd.closeexcept:print "error"error>>>还可以指定错误类型:
except ValueError:
except IOError:
考虑文件关闭有两种方式:一、使用try/except/finally机制。
试图打开一个不存在的文件,会发生崩溃,可以用except IOError处理异常,fianlly扩展try:里面放着无论任何情况都必须运行的代码,通常是文件关闭。
>>> try:data = open("missing.txt")print(data.readline(),end='')except IOError:print("File Error")finally:data.close()File ErrorTraceback (most recent call last): File "<pyshell#45>", line 7, in <module> data.close()NameError: name 'data' is not defined>>>崩溃是因为data打开的文件不存在,在finally里面增加判断条件:
>>> try:data = open("missing.txt")print(data.readline(),end='')except IOError:print("File Error")finally:if 'data' in locals():data.close()File Error>>>
给异常起名字
>>> try:data = open("missing.txt")print(data.readline(),end='')except IOError as err:print("File Error"+err)finally:if 'data' in locals():data.close()Traceback (most recent call last): File "<pyshell#49>", line 2, in <module> data = open("missing.txt")FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'During handling of the above exception, another exception occurred:Traceback (most recent call last): File "<pyshell#49>", line 5, in <module> print("File Error"+err)TypeError: Can't convert 'FileNotFoundError' object to str implicitly崩溃原因,异常类型与str不匹配:强制转化为 str(err)
>>> try:data = open("missing.txt")print(data.readline(),end='')except IOError as err:print("File Error"+str(err))finally:if 'data' in locals():data.close()File Error[Errno 2] No such file or directory: 'missing.txt'
二、使用with,python解释器会自动考虑为你关闭文件
try/except/finally机制会使代码冗长,with open语句则使得文件整洁。
>>> try:with open("missing.txt","r"):print(data.readline(),end='')except IOError as err:print("File Error"+str(err))File Error[Errno 2] No such file or directory: 'missing.txt'
4.pass放过错误
使用split()方法调用导致一个异常,可以报告这是一个错误并使用pass继续执行代码。也就是说python忽略了这个错误。
try/execpt/pass
如果用raise则表示不能放过这个错误,这段代码不能跳过
5.使用pickle腌制python数据,dump()腌制,load()取出
<pre name="code" class="python" style="font-size: 13.3333339691162px;">#coding: utf8import pickle#打开要读取的文件存入列表with open("F:/data/testB_checkins.csv","r") as fb:for i in range(10):mylist.append(fb.readline())#将读出的列表腌制到mydata.picklewith open("mydata.pickle","wb") as pickle_data:pickle.dump((mylist),pickle_data)#将腌制的数据取出来,仍然是列表的形式with open("mydata.pickle","rb") as read_data:newlist = pickle.load(read_data)
with open("F:/data/testB_checkins.csv","r") as fb:for i in range(10):mylist[i] = fb.readline()#下面是报错提示:Traceback (most recent call last): File "<pyshell#22>", line 3, in <module> mylist[i] = fb.readline()IndexError: list assignment index out of range报错原因:空数组索引下标越界,用append代替。
注意:(1)以二进制的方式读取、腌制。(2)用try/except pickle.pickleError捕获异常。正解:
#coding: utf8import pickle#打开要读取的文件存入列表with open("F:/data/testB_checkins.csv","r") as fb:for i in range(10):mylist.append(fb.readline())#将读出的列表腌制到mydata.picklewith open("mydata.pickle","wb") as pickle_data:pickle.dump((mylist),pickle_data)#将腌制的数据取出来,仍然是列表的形式with open("mydata.pickle","rb") as read_data:newlist = pickle.load(read_data)
6. raise停止运行
当程序出现错误,python会自动引发异常,也可以通过raise显示地引发异常。一旦执行了raise语句,raise后面的语句将不能执行。
test = 'abc'if True: raise test + 'def'
TypeError: exceptions must be old-style classes or derived from BaseException, not str
The sole argument to raise indicates the exception to be raised. This must be either an exception instance or an exception class (a class that derives from Exception).Try this:test = 'abc'if True: raise Exception(test + 'def')
0 0
- 《head first python》——文件与异常
- Head First Python(文件与异常)
- Python初入门(三)(Head First Python 第三章 文件与异常)
- 《head first python》——web开发
- Head First 设计模式—Python实现
- Head First Java(2)——数字与静态及异常处理
- Head First Python 学习笔记-Chapter3:文件读取和异常处理
- Head First Python——初识Python+列表
- 《head first python》——理解数据:列表排序与集合
- 《head first python》— 函数定义、模块与发布、共享代码
- 《head first python》——定制数据对象
- 《Head First Python》学习笔记03 异常处理
- Head First Python
- Head First Python 读书笔记
- 【阅读】《head first HTML与CSS》——前言
- Head First Python---------(一)第一章(初识Python__人人都爱列表)、第二章(共享你的代码__函数模块)、第三章(文件与异常__处理错误)
- 《Head First Programming》---python 5_哈希与数据库
- 《Head First Python》学习笔记
- HTTPConnection与HTTPClient
- 结合多线程、Socket的聊天小程序
- [HDU 4009] Transfer water 最小树形图
- 1054. The Dominant Color (20)
- Unity的 Stats 窗口, Batched、SetPass、Draw Call 等
- 《head first python》——文件与异常
- 百度UEditor的介绍和图片上传的使用(java)
- Android学习之浅谈selector与Shape用法
- 1.andriod 视图解析
- 64位32位windows7安装python34和python27,numpy,scipy,matplotlib,scikit-learn等第三方模块
- Android 安装应用后点击打开带来的问题
- 欢迎使用CSDN-markdown编辑器
- HYSBZ 1008 越狱 快速幂取模
- Java Security安全系列文档翻译笔记————KeyStore、密钥、证书、命令行实战