您现在的位置是:首页 > 编程开发 > Python > Python

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

编辑:站长来源:互联网作者: 佚名2020-07-03Python

简介1.查看当前路径,转到工作目录importosos.getcwd()\'C:\\\\Python27\'

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 "",line 1,in 
    (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

还可以指定错误类型:
<code class="language-python">except ValueError:
<code class="language-python">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
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
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
print("File Error"+err)
TypeError: Can't convert 'FileNotFoundError' object to str implicitly

崩溃原因,异常类型与str不匹配:强制转化为 str(err)
<code class="language-python">>>> 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'

<p style="font-size:13.3333339691162px;">二、使用with,python解释器会自动考虑为你关闭文件


<p style="font-size:13.3333339691162px;"><span style="font-size:13.3333339691162px;">try/except/finally机制会使代码冗长,with open语句则使得文件整洁。


<p style="font-size:13.3333339691162px;">

>> 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()取出


",line 3,in 
    mylist[i] = fb.readline()
IndexError: list assignment index out of range

注意:(1)以二进制的方式读取、腌制。

<pre style="font-size:13px;border:0px;overflow:auto;font-family:Consolas,Menlo,Monaco,'Lucida Console','Liberation Mono','DejaVu Sans Mono','Bitstream Vera Sans Mono','Courier New',monospace,sans-serif;color:rgb(34,34,34);background-color:rgb(238,238,238);"><code style="border:0px;font-size:13px;font-family:Consolas,sans-serif;">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:

<p style="font-size:13.3333339691162px;">

<code class="language-python">test = 'abc'
if True:
raise Exception(test + 'def')

很赞哦! ()

相关文章