Python_day7:错误捕获与处理

 

Python

PHP

错误捕获

try...except...else…finally...

可以不存在finally,如果有则会执行

else也可以没有,如果存在,当没有错误的时候会被执行

可以使用多个except来捕获不同类型的错误

 

错误类型其实是个类,继承于BaseException

并且会自动捕获当前错误类下的子类错误,不需要重复except

 

try…catch…

错误类型继承关系

BaseException

 +-- SystemExit

 +-- KeyboardInterrupt

 +-- GeneratorExit

 +-- Exception

      +-- StopIteration

      +-- StopAsyncIteration

      +-- ArithmeticError

      |    +-- FloatingPointError

      |    +-- OverflowError

      |    +-- ZeroDivisionError

      +-- AssertionError

      +-- AttributeError

      +-- BufferError

      +-- EOFError

      +-- ImportError

      |    +-- ModuleNotFoundError

      +-- LookupError

      |    +-- IndexError

      |    +-- KeyError

      +-- MemoryError

      +-- NameError

      |    +-- UnboundLocalError

      +-- OSError

      |    +-- BlockingIOError

      |    +-- ChildProcessError

      |    +-- ConnectionError

      |    |    +-- BrokenPipeError

      |    |    +-- ConnectionAbortedError

      |    |    +-- ConnectionRefusedError

      |    |    +-- ConnectionResetError

      |    +-- FileExistsError

      |    +-- FileNotFoundError

      |    +-- InterruptedError

      |    +-- IsADirectoryError

 

 

Python

PHP

 

      |    +-- NotADirectoryError

      |    +-- PermissionError

      |    +-- ProcessLookupError

      |    +-- TimeoutError

      +-- ReferenceError

      +-- RuntimeError

      |    +-- NotImplementedError

      |    +-- RecursionError

      +-- SyntaxError

      |    +-- IndentationError

      |         +-- TabError

      +-- SystemError

      +-- TypeError

      +-- ValueError

      |    +-- UnicodeError

      |         +-- UnicodeDecodeError

      |         +-- UnicodeEncodeError

      |         +-- UnicodeTranslateError

      +-- Warning

           +-- DeprecationWarning

           +-- PendingDeprecationWarning

           +-- RuntimeWarning

           +-- SyntaxWarning

           +-- UserWarning

           +-- FutureWarning

           +-- ImportWarning

           +-- UnicodeWarning

           +-- BytesWarning

           +-- ResourceWarning

 

logging模块

 

可以配置成日志记录模式

可以记录错误,并且不会停止程序

import logging
  def foo(s):
    return 10 / int(s)
  def bar(s):
    return foo(s) * 2
  def main():
    try:
        bar('0')
    except Exception as e:
        logging.exception(e)
main()
  print('END')

 

 

Python

PHP

错误抛出

raise

需要自己先定义一个错误类,选择正确的继承关系

 

或者是直接抛出错误描述

def foo(s):
    n = int(s)
    if n==0:
        raise ValueError('invalid value: %s' % s)
    return 10 / n
  def bar():
    try:
        foo('0')
    except ValueError as e:
        print('ValueError!')
        raise
  bar()

throw

 

Python

PHP

打开文件

f = open(' path', 'type ')

r:只读

w:清空写

a:追加写

 

二进制文件(图片、视频)

采用'rb'模式打开

 

读取非utf-8编码文本文件,需要第三个参数encoding='gbk'

 

编码错误的忽略方法,加入第四个参数

errors='ignore'

$f = fopen('path ', 'type ')

r:只读

r+:读写

w:清空后只写,文件不存在的时候会创建

w+:清空后读写,文件不存在的时候会创建

a:追加只写,文件不存在的时候会创建

a+:追加读写,文件不存在的时候会创建

 

读文件

f.read(size)读取指定长度

f.readline()读取一行

f.readlines()读取全部内容返回list

fread($f,size)

写文件

需要在'w'或'wb'模式下打开文件

f.write('content')

 

关闭文件

f.close()

自动调用写法

with open('/path/to/file', 'r') as f:

    print(f.read())

fclose($f)

内存读写

StringIO

 

使用getvalue()获取数据

from io import StringIO
f = StringIO()
f.write('hello')
f.write(' ')
f.write('world!')
  print(f.getvalue())

 

内存读写

BytesIO

 

 

from io import BytesIO
f = BytesIO()
f.write('中文'.encode('utf-8'))
  print(f.getvalue())

 

 

Python

PHP

操作文件和目录

 

 

系统信息

import os
  print(os.name)

 

 

 

环境变量

print(os.environ)

 

print(os.environ.get('key'))

 

 

操作文件和目录

函数分两个模块

os模块

os.path模块

 

查看当前目录绝对路径

print(os.path.abspath('.'))

 

 

路径拼接

print(os.path.join('/Users/michael', 'testdir'))

 

 

目录创建

os.mkdir('/Users/michael/testdir')

 

 

目录删除

os.rmdir('/Users/michael/testdir')

 

 

拆分路径

会把最后一部分的文件名切出来

print(os.path.split('/Users/michael/testdir/file.txt'))

 

 

获取文件扩展名

print(os.path.splitext('/path/to/file.txt'))

 

 

文件重命名

os.rename('test.txt', 'test.py')

 

 

文件删除

os.remove('test.py')

 

 

获取当前目录下的所有目录

print([x for x in os.listdir('.') if os.path.isdir(x)])

 

获取指定后缀名的文件

print( [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py'])

 

 

Python

PHP

序列化

picking

import pickle
d = dict(name='Bob', age=20, score=88)
  print(pickle.dumps(d))

 

serialize()

反序列化

unpicking

f= open('dump.txt', 'rb')
d = pickle.load(f)
  f.close()

 

unserialize()

json

import json
d = dict(name='Bob', age=20, score=88)
  print(json.dumps(d))

 

json_encode()

 

json_str = '{"age": 20, "score": 88, "name": "Bob"}'
  print(json.loads(json_str))

 

json_decode()

对象的json化

需要传入第二个参数default

import json
  
  class Student(object):
    def __init__(self, name, age, score):
        self.name = name
        self.age = age
        self.score = score
  
  s = Student('Bob', 20, 88)
  print(json.dumps(s,default=lambda obj: obj.__dict__))

 

 

json对象化

json_str = '{"age": 20, "score": 88, "name": "Bob"}'
  def dict2student(d):
    return Student(d['name'], d['age'], d['score'])
  print(json.loads(json_str, object_hook=dict2student))

 

 

猜你喜欢

转载自blog.csdn.net/zhq_zvik/article/details/80622207
今日推荐