hncys 发表于 2018-8-15 12:18:32

python 高级

  使用到的函数在python3.5是open,在python2.7同时支持file和open
打开方式
  文件句柄=open('文件路径','打开模式')
  文件句柄相当于变量名。
  打开文件的模式
  r :只读,文件必须存在
  w:只写,文件不存在则创建,存在则清空
  x:只写,文件不可读,不存在则创建,存在则报错
  a:追加, 文件不存在则创建,存在则在末尾添加内容
  r+:读写
  w+:写读
  x+:写读
  a+:写读
  rb:二进制读
  wb:二进制写
  xb:二进制只写
  ab:二进制追加
  以b方式打开的,读取到的内容是字节内心,写入时也需要提供字节类型
  rb+:二进制读写
  wb+:二进制读写
  xb+:二进制只写
  ab+:二进制读写
文件读取方式
  read():读取文件全部内容,设置了size,读取size字节
  readline():一行一行的读取
  readlines():读取到的每一行内容作为列表中的一个元素
文件写入方式
  write(str):将字符串写如文件
  writelines(sequence or strings):写多行到文件,参数可以是一个可迭代的对象、列表、元组等。
文件操作的方法
  close
  flush
  isatty
  readable
  tell
  seek
  seekable
  writable
同时打开多个文件
  避免打开文件后忘记关闭,可以通过管理上下文
  with open('log', 'r') as f:
  statement
  当with执行完毕时,内部会自动关闭并释放文件资源。
  with又支持同时对多个文件的上下文管理
  with open('log1') as obj1, open('log2') as obj2:
  statement
python装饰器
  装饰器是由函数去生成的,用于装饰某个函数或者方法或者类,他可以让这个函数在执行之前或者执行之后做一些操作。

[*]#!/usr/bin/env python  
# _*_ coding: utf-8 _*_
  
def decorator(func):# 创建一个装饰器函数,接受的参数arg参数就是func函数名
  
    def inner(*args, **kwargs):
  
      print("执行函数之前")
  
      ret = func(*args, **kwargs)
  
      print("执行函数之后")
  
      return ret
  
    return inner
  
@decorator# 如果要让某个函数使用装饰器,只需要在这个函数上面加上@+装饰器名
  
def func(arg):
  
    print(arg)
  
func("Hello World!")
  多个装饰器装饰同一个函数。

[*]#!/usr/bin/env python  
# _*_ coding: utf-8 _*_
  
def decorator1(func):
  
    def inner():
  
      print("开始之前执行装饰器01")
  
      ret = func()
  
      print("结束之后执行装饰器01")
  
      return ret
  
    return inner
  
def decorator2(func):
  
    def inner():
  
      print("decorator2>>>Start...")
  
      ret = func()
  
      print("decorator2>>>End...")
  
      return ret
  
    return inner
  
@decorator1
  
@decorator2
  
def index():
  
    print("执行函数...")
  
index()
  python正则
  python字符串格式化
  python迭代器生成器
  python反射
  python设计模式
  python异常处理
页: [1]
查看完整版本: python 高级