您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:25:26 python 字数 11698 阅读 803 来源 www.jb51.cc/python

1.查看当前路径,转到工作目录 >>>importos >>>os.getcwd() \'C:\\\\Python27\'

概述

1. 查看当前路径,转到工作目录

>> import os
>>> os.getcwd()
'C:\\Python27'
>>> os.chdir("F:/data")
>>> os.getcwd()
'F:\\data'
>> 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

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

File Error
Traceback (most recent call last):
File "<pyshell#45>",line 7,in
data.close()
NameError: name 'data' is not defined

File Error
Traceback (most recent call last):
File "<pyshell#45>",line 7,in
data.close()
NameError: name 'data' is not defined

>> try:
    data = open("missing.txt")
    print(data.readline(),end='')
except IOError:
    print("File Error")
finally:
    if 'data' in locals():
        data.close()

File Error

File Error

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

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

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

<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'

File Error[Errno 2] No such file or directory: 'missing.txt'

File Error[Errno 2] No such file or directory: 'missing.txt'

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

>> 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'

File Error[Errno 2] No such file or directory: 'missing.txt'

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

文件存入列表
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)
提示:
Traceback (most recent call last):
  File "
  
   ",line 3,in 
   
    
    mylist[i] = fb.readline()
IndexError: list assignment index out of range

   
  
文件存入列表
with open("F:/data/testB_checkins.csv","rb") as read_data:
    newlist = pickle.load(read_data)

6. raise停止运行

错误,python会自动引发异常,也可以通过raise显示地引发异常。一旦执行了raise语句,raise后面的语句将不能执行。

<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')

总结

以上是编程之家为你收集整理的《head first python》——文件与异常全部内容,希望文章能够帮你解决《head first python》——文件与异常所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶