《head first python》——文件与异常

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 = fd
	try:
		data1 = fd1
	except:
		pass
	fd.close
except:
	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 Error
Traceback (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: utf8
import pickle
#打开要读取的文件存入列表
with open("F:/data/testB_checkins.csv","r") as fb:
	for i in range(10):
		mylist.append(fb.readline())
#将读出的列表腌制到mydata.pickle
with 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: utf8
import pickle
#打开要读取的文件存入列表
with open("F:/data/testB_checkins.csv","r") as fb:
	for i in range(10):
		mylist.append(fb.readline())
#将读出的列表腌制到mydata.pickle
with 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')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值