zoukankan      html  css  js  c++  java
  • Python之路【第五篇】python基础 之初识函数(一)和文件管理

     

     转载请注明出处http://www.cnblogs.com/wupeiqi/articles/5453708.html

    函数                                                                             

    一、背景                                                                                                                 

    在学习函数之前,一直遵循:面向过程编程,即:根据业务逻辑从上到下实现功能,其往往用一长段代码来实现指定功能,开发过程中最常见的操作就是粘贴复制,也就是将之前实现的代码块复制到现需功能处,如下:

     1 while True:
     2     if cpu利用率 > 90%:
     3         #发送邮件提醒
     4         连接邮箱服务器
     5         发送邮件
     6         关闭连接
     7     
     8     if 硬盘使用空间 > 90%:
     9         #发送邮件提醒
    10         连接邮箱服务器
    11         发送邮件
    12         关闭连接
    13     
    14     if 内存占用 > 80%:
    15         #发送邮件提醒
    16         连接邮箱服务器
    17         发送邮件
    18         关闭连接

    一看上述代码,if条件语句下的内容可以被提取出来公用,如下:

     1 def 发送邮件(内容)
     2     #发送邮件提醒
     3     连接邮箱服务器
     4     发送邮件
     5     关闭连接
     6     
     7 while True:
     8     
     9     if cpu利用率 > 90%:
    10         发送邮件('CPU报警')
    11     
    12     if 硬盘使用空间 > 90%:
    13         发送邮件('硬盘报警')
    14     
    15     if 内存占用 > 80%:

    对于上述的两种实现方式,第二次必然比第一次的重用性和可读性要好,其实这就是函数式编程和面向过程编程的区别:

    • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
    • 面向对象:对函数进行分类和封装,让开发“更快更好更强...”

    函数式编程最重要的是增强代码的重用性和可读性

    二、定义和使用                                                                              

    1 def 函数名(参数):
    2        
    3     ...
    4     函数体
    5     ...
    6     返回值

    函数的定义主要有如下要点:

    • def:表示函数的关键字
    • 函数名:函数的名称,日后根据函数名调用函数
    • (参数)
    • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
    • 参数:为函数体提供数据
    • 返回值:当函数执行完毕后,可以给调用者返回数据。

    1、返回值

    函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

    以上要点中,比较重要有参数和返回值: 1 def 发送短信():   

     2     发送短信的代码...
     3     if 发送成功:
         #在函数中,一旦执行return,函数执行过程立即终
    4 return True 5 else: 6 return False 7 8 while True: 9 # 每次执行发送短信函数,都会将返回值自动赋值给result 10 # 之后,可以根据result来写日志,或重发等操作 11 result = 发送短信() 12 if result == False: 13 记录日志,短信发送失败...

       返回值数=0:返回None

       返回值数=1:返回object

       返回值数>1:返回tuple

    2、参数

    • 1.形参变量只有在被调用时才分配内存单元,在调用结束时,即刻释放所分配的内存单元。因此,形参只在函数内部有效。函数调用结束返回主调用函数后则不能再使用该形参变量
    • 2.实参可以是常量、变量、表达式、函数等,无论实参是何种类型的量,在进行函数调用时,它们都必须有确定的值,以便把这些值传送给形参。因此应预先用赋值,输入等办法使参数获得确定值

    函数的有三中不同的参数:

    • 普通参数
    • 默认参数
    • 动态参数
        •  定义函数  (形参和实参)普通参数
     1 # ######### 定义函数 ######### 
     2 
     3 # name 叫做函数func的形式参数,简称:形参
     4 def func(name):
     5     print(name)
     6  7 # ######### 执行函数 #########   8 # 'xiaoming' 叫做函数func的实际参数,简称:实参  9 func('xiaoming') 10 11 普通参数
        •  默认参数
    1 # name 叫做函数func的形式参数,简称:形参
    2 # def func(name, age=18):  #age 是默认参数  如果下面没有指定参数,就直接用默认参数
    3 #     print("%s:%s" % (name, age))
    4 #
    5 #
    6 # # 指定参数
    7 # func('wupeiqi', 19)  #19 替代了默认参数
    8 # # 使用默认参数
    9 # func('alex')
        • 动态参数   
    def func(*args):
        print(args)
    # 执行方式一
    func(11,33,4,4454,5)
    # 执行方式二
    li = [11,2,2,3,3,4,54]
    func(*li)
    # 动态参数
    def func(**kwargs):
        print(kwargs)
    # 执行方式一
    func(name = 'wupeiqi',age=18)
    # 执行方式二
    li = {'name':'wupeiqi', "age":18, 'gender':'male'}
    func(**li)
    #动态参数
        • 万能参数     
    1 def f1(*args,**kwargs):
    2     print(args)
    3     print(kwargs)
    4  
    5 f1(11,22,33,44,k1='v1',k2='v2')

    注意:*args,**kwargs顺序不能改变。

     3、全局变量和局部变量

     1 # 全局变量 与 局部变量
     2 # name = "lhf"  #全局变量 任何位置都可以调用
     3 # def change_name():
     4 #     name = "shuai" #局部变量
     5 #     print("change_name",name)  #如果没有局部变量直接调用全局变量,如果有直接调用局部变量
     6 # change_name()
     7 # print(name)
     8 
     9 # globals()    关键字的用法
    10 # name = "lhf"
    11 # def change_name():
    12 #     global name  #调用全局变量
    13 #     name = "shuai"  #给全局变量赋值
    14 #     print("change_name",name)
    15 # change_name()
    16 # print(name)
    17 
    18 NAME = "产品经理"
    19 def yangjiang():
    20     #NAME = "史正文"
    21     global NAME  #已经声明,NAME 就是全局的那个变量
    22     NAME = "小东北"  #修改 全局的变量
    23     print("我要搞",NAME)
    24 def qupengfei():
    25     #NAME = "基"
    26     print("我要搞",NAME)
    27 yangjiang()
    28 qupengfei()
    29 # 如果函数中没有global关键字,
    30     # 有声明局部变量
    31         # NAME = ["产品经理","廖博士"]
    32         # def qupengfei():
    33         #     NAME = "myself"
    34         #     print("我要搞",NAME)
    35         # qupengfei()
    36     # 无声明局部变量
    37     #     NAME = ["产品经理","廖博士"]
    38     #     def qupengfei():
    39     #         #NAME = "myself"
    40     #         NAME.append("123")
    41     #         print("我要搞",NAME)
    42     #     qupengfei()
    43 #
    44 #
    45         # 优先读取局部变量如果没有, 能读取全局变量,无法对全局变量重新赋值
    46         #对于可变对象,可以对内部元素进行操作
    47 #如果函数中有global关键字,
    48     # 有声明局部变量
    49     #     NAME = ["产品经理","廖博士"]
    50     #     def qupengfei():
    51     #         global NAME
    52     #         NAME = "myself"
    53     #         print("我要搞",NAME)
    54     #       qupengfei()
    55     #错误示例
    56     #     NAME = ["产品经理","廖博士"]
    57     #     def qupengfei():
    58     #         NAME = "myself"
    59     #         global NAME
    60     #         print("我要搞",NAME)
    61     #     qupengfei()
    62 
    63     # 无声明局部变量
    64         # NAME = ["产品经理","廖波湿"]
    65         # def qupengfei():
    66         #     global NAME
    67         #     NAME = ["阿毛"]
    68         #     NAME.append('XXOO')
    69         #     print('我要搞', NAME)
    70         # qupengfei()
    71 
    72 
    73 
    74 # 变量本质上就是全局变量, 可能读取全局变量,可对全局变量重新赋值
    75 
    76 # NAME = ["产品经理","廖博士"]
    77 # def yangjiang():
    78 #     #NAME = "史正文"
    79 #     global NAME  #已经声明,NAME 就是全局的那个变量
    80 #     NAME = "小东北"  #修改 全局的变量
    81 #     print("我要搞",NAME)
    82 # def qupengfei():
    83 #     #NAME = "基"
    84 #     print("我要搞",NAME)
    85 # yangjiang()
    86 # qupengfei()
    全局变量 与 局部变
     1 #  函数的嵌套
     2 # NAME = "海风"
     3 # def huangwei():
     4 #     name = "黄威"
     5 #     print(name)
     6 #     def liuyang():
     7 #         name = "刘洋"
     8 #         print(name)
     9 #         def nulige():
    10 #             name = "胡志华"
    11 #             print(name)
    12 #         print(name)
    13 #         nulige()
    14 #     liuyang()
    15 #     print(name)
    16 # huangwei()
    17 # print(NAME)
    18 
    19 # name = "刚娘"
    20 # def weihou():
    21 #     name = "陈卓"
    22 #     def weiweihou():
    23 #         nonlocal name # nanlocal ,指定上一次变量 如果没找到直接直接在往上找,不会找到全局变量
    24 #         name = "冷静"
    25 #     weiweihou()
    26 #     print(name)
    27 # print(name)
    28 # weihou()
    29 # print(name)

     4、递归

    在函数内部,可以调用其他函数。如果一个函数在内部调用自身本身,这个函数就是递归函数。

     1 #  问路题
     2 # import time
     3 # person_list = ["alex","wupeiqi,","yuanhao","linhaifeng"]
     4 # def ask_way(person_list):
     5 #     print('-'*60)
     6 #     if len(person_list) == 0 :
     7 #         return "没人知道"
     8 #     person = person_list.pop(0)
     9 #     if person == "linhaifeng":
    10 #         return '%s说:我知道,老男孩就在沙河汇德商厦,下地铁就是' %person
    11 #     print('hi 美男[%s],敢问路在何方' % person)
    12 #     print('%s回答道:我不知道,但念你慧眼识猪,你等着,我帮你问问%s...' % (person, person_list))
    13 #     time.sleep(3)
    14 #     res = ask_way(person_list)
    15 #     print('%s问的结果是: %res' % (person, res))
    16 #     return res
    17 # res =ask_way(person_list)
    18 # print(res)
    19 
    20 # def cur(n):  # 定义一个函数
    21 #     print(n) #打印出入的值
    22 #     if int(n/2) == 0 :   #判断n/2的值是否==0
    23 #         return n    #直接结束程序
    24 #     return cur(int(n/2)) #递归
    25 # cur(10)
    两个递归示例

    递归特性:

    1. 必须有一个明确的结束条件

    2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少

    3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

     
    递归算法是一种直接或者间接地调用自身算法的过程。在计算机编写程序中,递归算法对解决一大类问题是十分有效的,它往往使算法的描述简洁而且易于理解。
     
    递归算法解决问题的特点:
    • 递归就是在过程或函数里调用自身。
    • 在使用递归策略时,必须有一个明确的递归结束条件,称为递归出口。
    • 递归算法解题通常显得很简洁,但递归算法解题的运行效率较低。所以一般不提倡用递归算法设计程序。
    • 递归调用的过程当中系统为每一层的返回点、局部量等开辟了栈来存储。递归次数过多容易造成栈溢出等。所以一般不提倡用递归算法设计程序。
     1 def fact_iter(product,count,max):
     2     if count > max:
     3         return product
     4     return fact_iter(product * count, count+1, max)
     5  
     6 print(fact_iter(1,1,5))
     7 print(fact_iter(1,2,5))
     8 print(fact_iter(2,3,5))
     9 print(fact_iter(6,4,5))
    10 print(fact_iter(24,5,5))
    11 print(fact_iter(120,6,5))
    递归

    三、内置函数     

     

      1 # 1. 绝对值
      2 # i = abs(-123)
      3 # print(i)
      4 
      5 # 2 all 循环参数,如果每个元素都为真,那么all的返回值为真
      6 # r = all([1,2,3,True,False])
      7 # print(r)
      8 
      9 # 3 any 循环参数,如果元素有一真,那么any的返回值为真
     10 # i = any([None,'',{},[],(),0,1])
     11 # print(i)
     12 
     13 # 4
     14 # bin() # 二进制 0b1011 ob 代表2进制
     15 # print(bin(11))
     16 # oct() # 八进制
     17 # int() # 十进制
     18 # hex() # 十六进制
     19 
     20 # 5
     21 # bool ,判断真假,把一个对象转换成布尔值
     22 
     23 # 6
     24 # str
     25 # list
     26 
     27 # bytes  字节
     28 # bytearray  字节列表
     29 # 字节和字符串之间的转换
     30 # print(bytes("112",encoding="gbk"))
     31 
     32 # 7
     33 # chr(33)  # 查看ASCII 中对应的字符
     34 # ord("t") #  查看字符对应的位置
     35 # # ascii 一个字节,8位,2**8 ,256
     36 
     37 # 8 做编译用,把一段字符串编译成一段可执行的代码
     38 # compile()
     39 
     40 # 9 得到商和余数商3余1
     41 # r = divmod(10,3)
     42 # print(r)
     43 
     44 # 10 可以执行一个字符串形式的表达式
     45 # ret = eval("1 + 3") # 表达式,返回值
     46 # print(ret)
     47 # exec 执行py代码
     48 # evel 表达式,返回值
     49 # compile 编译
     50 
     51 # 11
     52 # filter(函数,可迭代对象) 过滤
     53 # def f(x):
     54 #     if x >22:
     55 #         return True
     56 #     else:
     57 #         return False
     58 # ret = filter(f,[11,22,33,44,55])
     59 # print(list(ret))
     60 # ret = filter(lambda x:x>22,[11,22,33,44,55])
     61 # print(list(ret))
     62 
     63 # 12 map(函数,可迭代对象)
     64 # ret = map(lambda x:x+100,[1,2,3,4,5])
     65 # print(list(ret))
     66 # ret = map(lambda x:x+100 if x%2 == 0 else x ,[1,2,3,4,5])
     67 # print(list(ret))
     68 
     69 # 13
     70 # globals() # 获取所有的全局变量
     71 # locals()
     72 # def f1():
     73 #     name = 123
     74 #     print(locals())
     75 #     print(globals())
     76 # f1()
     77 
     78 # 14  判断某个对象是否是某个类创建的
     79 # li = [11,22,33]
     80 # r = isinstance(li,list)
     81 # print(r)
     82 
     83 # 15 创建一个可被迭代的东西
     84 # obj = iter([11,22,33,44])
     85 # r1 = next(obj)
     86 # # next 调用迭代的对象的值
     87 # print(r1)
     88 
     89 # 16
     90 # max()#取最大值
     91 # min()#取最小值
     92 
     93 # 17 求指数2的10次方
     94 # i = pow(2,10)
     95 # print(i)
     96 
     97 # 18 四舍五入
     98 # r = round(3.6)
     99 # print(r)
    100 
    101 # 19 求和
    102 # sum()
    103 
    104 # 20  一一对应
    105 # zip()
    106 # li = [11,22,33,44]
    107 # l1 = ['a','b','c','d']
    108 # r = zip(li,l1)
    109 # print(list(r)) # 结果:[(11, 'a'), (22, 'b'), (33, 'c'), (44, 'd')]
    110 
    111 # 21 排序,同种类型
    112 # li = [1,211,22,3,4]
    113 # # print(li )
    114 # # li.sort()
    115 # # print(li)
    116 #
    117 # new_li = sorted(li)
    118 # print(new_li)
    内置函数

      注:查看详细猛击这里     

    内置函数map 、  filter、reduce

    1、map

    遍历序列,对序列中每个元素进行操作,最终获取新的序列

     1 # num =[1,2,3,4,5,11]
     2 # def add(x):
     3 #     return x+1
     4 # def reduce(x):
     5 #     return x-1
     6 # def pf(x):
     7 #     return x**2
     8 # def map_text(func,array):
     9 #     ret = []
    10 #     for i in array:
    11 #         res = func(i)     #相当于传入下面函数调用的
    12 #         ret.append(res)
    13 #     return ret
    14 # print(map_text(add,num))
    15 # print(map_text(reduce,num))
    16 # print(map_text(pf,num))
    17 
    18 # num =[1,2,3,4,5,11]
    19 # print(map_text(lambda x:x**2,num))
    20 
    21 ############### 终极版#############
    22 # num =[1,2,3,4,5,11]
    23 # def map_text(func,array): #func = lambda x:x+1 array = [1,2,3,4,5,11]
    24 #     ret = []
    25 #     for i in array:
    26 #         res = func(i)     #相当于传入下面函数调用的
    27 #         ret.append(res)
    28 #     return ret
    29 # print(map_text(lambda x:x+1,num))
    30 #  最终版本
    31 # num =[1,2,3,4,5,11]
    32 # print(list(map(lambda x:x+1,num)))  # 需要用list处理结果
    map 实现过程

    2、filter

    对于序列中的元素进行筛选,最终获取到符合条件的序列

     1 ######################## filter 用法  ################################
     2 
     3 # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
     4 
     5 
     6 
     7 
     8 # def filter_test(array):
     9 #     ret=[]
    10 #     for p in array:
    11 #         if not p.startswith('sb'):
    12 #                ret.append(p)
    13 #     return ret
    14 #
    15 # res=filter_test(movie_people)
    16 # print(res)
    17 
    18 
    19 # movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
    20 # def sb_show(n):
    21 #     return n.endswith('sb')
    22 #
    23 # def filter_test(func,array):
    24 #     ret=[]
    25 #     for p in array:
    26 #         if not func(p):
    27 #                ret.append(p)
    28 #     return ret
    29 #
    30 # res=filter_test(sb_show,movie_people)
    31 # print(res)
    32 
    33 #终极版本
    34 # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
    35 
    36 # def filter_test(array):
    37 #     ret = []
    38 #     for p in array:
    39 #         if not p.startswith("sb"):
    40 #             ret.append(p)
    41 #     return ret
    42 # print(filter_test(movie_people))
    43 
    44 # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
    45 # def filter_test(func,array):
    46 #     ret = []
    47 #     for p in array:
    48 #         if not func(p):
    49 #             ret.append(p)
    50 #     return ret
    51 # print(filter_test(lambda n:n.startswith("sb"),movie_people))
    52 
    53 # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
    54 # print(list(filter(lambda n:not n.startswith("sb"),movie_people)))
    55 
    56 # form functools import reduce
    filter

    3、reduce

    对于序列内所有元素进行累计操作

     1 # form functools import reduce
     2 # num =  [1,2,3,4,5,6,100]
     3 # res = 0
     4 # for n in num :
     5 #     res += n
     6 # print(res)
     7 
     8 # num =  [1,2,3,4,5,6,100]
     9 # def reduce_test(array):
    10 #     res = 0
    11 #     for n in num :
    12 #         res += n
    13 #     return res
    14 # print(reduce_test(num))
    15 
    16 # num =  [1,2,3,100]
    17 # def reduce_test(func,array):
    18 #     res = array.pop(0)
    19 #     for n in array :
    20 #         res = func(res,n)
    21 #     return res
    22 # print(reduce_test(lambda x,y:x*y,num))
    23 
    24 # from functools import reduce
    25 # num =  [1,2,3,100]
    26 # reduce(lambda x,y:x*y,num,3)
    27 # print(reduce(lambda x,y:x*y,num,3))
    reduce

      1 # map处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样 2 #filter遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来 3 #reduce:处理一个序列,然后把序列进行合并操作 

     文件处理                                                                     

    open函数,该函数用于文件处理

    操作文件时,一般需要经历如下步骤:

    • 打开文件
    • 操作文件

    一、打开文件

          1 文件句柄 = open('文件路径(文件名)', '模式',‘encoding= 'utf-8’) 

    打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

    打开文件的模式有:

    • r ,只读模式【默认】
    • w,只写模式【不可读;不存在则创建;存在则清空内容;】
    • x, 只写模式【不可读;不存在则创建,存在则报错】
    • a, 追加模式【不可读;   不存在则创建;存在则只追加内容;】

    "+" 表示可以同时读写某个文件

    • r+, 读写【可读,可写】
    • w+,写读【可读,可写】
    • x+ ,写读【可读,可写】
    • a+, 写读【可读,可写】

     "b"表示以字节的方式操作

    • rb  或 r+b
    • wb 或 w+b
    • xb 或 w+b
    • ab 或 a+b

     注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型

    二、操作

     1 # 1、open(文件名,模式,编码) #打开方式
     2 # 默认是只读模式
     3 # f = open("log",'r')
     4 # data = f.read()
     5 # f.closed
     6 # print(data)
     7 
     8 # 1 只读 r
     9 # f = open("log","r",encoding='utf-8')
    10 # f.closed
    11 # 2 只写 w  不可读 ;文件不存在直接创建新文件,文件存在清空文件内容
    12 # f = open("log1",'w',encoding='utf-8')
    13 # # f.write('123')
    14 # f.closed
    15 # 3  只写模式 x 不存在创建,存在报错
    16 # f = open('log2','x',encoding='utf-8')
    17 # f.write('hello')
    18 # f.closed
    19 # 4 a 追加模式 不可读,不存在创建:存在则只追加内容
    20 # f = open('log2','a',encoding='utf-8')
    21 # f.write('
    666')
    22 # f.closed
    23 
    24 ##########字节方式打开 open(文件名,模式)
    25 # 1、只读 rb
    26 # f = open('log','rb')
    27 # data = f.read()
    28 # f.closed
    29 # print(data)
    30 # 2、只写wb
    31 # f = open('log2','wb')
    32 # f.write(bytes('中国',encoding='utf8'))  #将字符串转换成字节
    33 # f.closed
    34 
    35 # r/w/x/a  >>> 字符串
    36 # rb/wb/xb/ab/ >>>字节
    37 
    38 # "+" 表示可以同时读写某个文件
    39 #
    40 # r+, 读写【可读,可写】
    41 # w+,写读【可读,可写】
    42 # x+ ,写读【可读,可写】
    43 # a+, 写读【可读,可写】
    44 
    45 # #### r+, 读写【可读,可写】
    46 # w,末尾追加,指针最后
    47 # f = open('log',"r+",encoding='utf8')
    48 # # 光标的为0 ,起始位置
    49 # print(f.tell()) # 查看光标的位置
    50 # data = f.read(1)
    51 #
    52 # print(type(data),data)
    53 #
    54 # # f.write('德国人')
    55 # print(f.tell())
    56 #
    57 # # f.seek(0) # 以字节来讲,移动指针的位置
    58 #
    59 # data = f.read()
    60 # print(type(data),data)
    61 # f.closed
    62 
    63 # ###w+ 先清空,在写的之后,就可以写了
    64 # f = open("log",'w+',encoding="utf8")
    65 # f.write('何丽丽')
    66 # f.seek(0)
    67 # data = f.read()
    68 # print(data)
    69 # f.closed
    70 
    71 #####################操作##############
    72 # 1、
    73 # f = open('log','r+',encoding='utf8')
    74 # f.write('haoran')
    75 # f.flush() #把写的内容刷到硬盘去
    76 # 2
    77 # f = open('log','a+',encoding='utf8')
    78 # a+ 的指针的位置在最后
    79 # f.read()
    80 # 读取所有的内容read(1)字符 read(1) b 字节
    81 
    82 # 3
    83 # f = open('log','a+',encoding='utf8')
    84 # f.seek(0)
    85 # data =  f.readline()
    86 # print(data)
    87 
    88 # 4
    89 # f = open('log','r+',encoding='utf8')
    90 # print(f.tell())
    91 # print(f.seek(8))
    92 # # 依赖指针截取前面的位置
    93 # f.truncate()
    94 # f.closed
    文件操作
      1 class file(object)
      2     def close(self): # real signature unknown; restored from __doc__
      3         关闭文件
      4         """
      5         close() -> None or (perhaps) an integer.  Close the file.
      6          
      7         Sets data attribute .closed to True.  A closed file cannot be used for
      8         further I/O operations.  close() may be called more than once without
      9         error.  Some kinds of file objects (for example, opened by popen())
     10         may return an exit status upon closing.
     11         """
     12  
     13     def fileno(self): # real signature unknown; restored from __doc__
     14         文件描述符  
     15          """
     16         fileno() -> integer "file descriptor".
     17          
     18         This is needed for lower-level file interfaces, such os.read().
     19         """
     20         return 0    
     21  
     22     def flush(self): # real signature unknown; restored from __doc__
     23         刷新文件内部缓冲区
     24         """ flush() -> None.  Flush the internal I/O buffer. """
     25         pass
     26  
     27  
     28     def isatty(self): # real signature unknown; restored from __doc__
     29         判断文件是否是同意tty设备
     30         """ isatty() -> true or false.  True if the file is connected to a tty device. """
     31         return False
     32  
     33  
     34     def next(self): # real signature unknown; restored from __doc__
     35         获取下一行数据,不存在,则报错
     36         """ x.next() -> the next value, or raise StopIteration """
     37         pass
     38  
     39     def read(self, size=None): # real signature unknown; restored from __doc__
     40         读取指定字节数据
     41         """
     42         read([size]) -> read at most size bytes, returned as a string.
     43          
     44         If the size argument is negative or omitted, read until EOF is reached.
     45         Notice that when in non-blocking mode, less data than what was requested
     46         may be returned, even if no size parameter was given.
     47         """
     48         pass
     49  
     50     def readinto(self): # real signature unknown; restored from __doc__
     51         读取到缓冲区,不要用,将被遗弃
     52         """ readinto() -> Undocumented.  Don't use this; it may go away. """
     53         pass
     54  
     55     def readline(self, size=None): # real signature unknown; restored from __doc__
     56         仅读取一行数据
     57         """
     58         readline([size]) -> next line from the file, as a string.
     59          
     60         Retain newline.  A non-negative size argument limits the maximum
     61         number of bytes to return (an incomplete line may be returned then).
     62         Return an empty string at EOF.
     63         """
     64         pass
     65  
     66     def readlines(self, size=None): # real signature unknown; restored from __doc__
     67         读取所有数据,并根据换行保存值列表
     68         """
     69         readlines([size]) -> list of strings, each a line from the file.
     70          
     71         Call readline() repeatedly and return a list of the lines so read.
     72         The optional size argument, if given, is an approximate bound on the
     73         total number of bytes in the lines returned.
     74         """
     75         return []
     76  
     77     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
     78         指定文件中指针位置
     79         """
     80         seek(offset[, whence]) -> None.  Move to new file position.
     81          
     82         Argument offset is a byte count.  Optional argument whence defaults to
     83 (offset from start of file, offset should be >= 0); other values are 1
     84         (move relative to current position, positive or negative), and 2 (move
     85         relative to end of file, usually negative, although many platforms allow
     86         seeking beyond the end of a file).  If the file is opened in text mode,
     87         only offsets returned by tell() are legal.  Use of other offsets causes
     88         undefined behavior.
     89         Note that not all file objects are seekable.
     90         """
     91         pass
     92  
     93     def tell(self): # real signature unknown; restored from __doc__
     94         获取当前指针位置
     95         """ tell() -> current file position, an integer (may be a long integer). """
     96         pass
     97  
     98     def truncate(self, size=None): # real signature unknown; restored from __doc__
     99         截断数据,仅保留指定之前数据
    100         """
    101         truncate([size]) -> None.  Truncate the file to at most size bytes.
    102          
    103         Size defaults to the current file position, as returned by tell().
    104         """
    105         pass
    106  
    107     def write(self, p_str): # real signature unknown; restored from __doc__
    108         写内容
    109         """
    110         write(str) -> None.  Write string str to file.
    111          
    112         Note that due to buffering, flush() or close() may be needed before
    113         the file on disk reflects the data written.
    114         """
    115         pass
    116  
    117     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
    118         将一个字符串列表写入文件
    119         """
    120         writelines(sequence_of_strings) -> None.  Write the strings to the file.
    121          
    122         Note that newlines are not added.  The sequence can be any iterable object
    123         producing strings. This is equivalent to calling write() for each string.
    124         """
    125         pass
    126  
    127     def xreadlines(self): # real signature unknown; restored from __doc__
    128         可用于逐行读取文件,非全部
    129         """
    130         xreadlines() -> returns self.
    131          
    132         For backward compatibility. File objects now include the performance
    133         optimizations previously implemented in the xreadlines module.
    134         """
    135         pass
    136 
    137 2.x
    2.x
      1 class TextIOWrapper(_TextIOBase):
      2     """
      3     Character and line based layer over a BufferedIOBase object, buffer.
      4     
      5     encoding gives the name of the encoding that the stream will be
      6     decoded or encoded with. It defaults to locale.getpreferredencoding(False).
      7     
      8     errors determines the strictness of encoding and decoding (see
      9     help(codecs.Codec) or the documentation for codecs.register) and
     10     defaults to "strict".
     11     
     12     newline controls how line endings are handled. It can be None, '',
     13     '
    ', '
    ', and '
    '.  It works as follows:
     14     
     15     * On input, if newline is None, universal newlines mode is
     16       enabled. Lines in the input can end in '
    ', '
    ', or '
    ', and
     17       these are translated into '
    ' before being returned to the
     18       caller. If it is '', universal newline mode is enabled, but line
     19       endings are returned to the caller untranslated. If it has any of
     20       the other legal values, input lines are only terminated by the given
     21       string, and the line ending is returned to the caller untranslated.
     22     
     23     * On output, if newline is None, any '
    ' characters written are
     24       translated to the system default line separator, os.linesep. If
     25       newline is '' or '
    ', no translation takes place. If newline is any
     26       of the other legal values, any '
    ' characters written are translated
     27       to the given string.
     28     
     29     If line_buffering is True, a call to flush is implied when a call to
     30     write contains a newline character.
     31     """
     32     def close(self, *args, **kwargs): # real signature unknown
     33         关闭文件
     34         pass
     35 
     36     def fileno(self, *args, **kwargs): # real signature unknown
     37         文件描述符  
     38         pass
     39 
     40     def flush(self, *args, **kwargs): # real signature unknown
     41         刷新文件内部缓冲区
     42         pass
     43 
     44     def isatty(self, *args, **kwargs): # real signature unknown
     45         判断文件是否是同意tty设备
     46         pass
     47 
     48     def read(self, *args, **kwargs): # real signature unknown
     49         读取指定字节数据
     50         pass
     51 
     52     def readable(self, *args, **kwargs): # real signature unknown
     53         是否可读
     54         pass
     55 
     56     def readline(self, *args, **kwargs): # real signature unknown
     57         仅读取一行数据
     58         pass
     59 
     60     def seek(self, *args, **kwargs): # real signature unknown
     61         指定文件中指针位置
     62         pass
     63 
     64     def seekable(self, *args, **kwargs): # real signature unknown
     65         指针是否可操作
     66         pass
     67 
     68     def tell(self, *args, **kwargs): # real signature unknown
     69         获取指针位置
     70         pass
     71 
     72     def truncate(self, *args, **kwargs): # real signature unknown
     73         截断数据,仅保留指定之前数据
     74         pass
     75 
     76     def writable(self, *args, **kwargs): # real signature unknown
     77         是否可写
     78         pass
     79 
     80     def write(self, *args, **kwargs): # real signature unknown
     81         写内容
     82         pass
     83 
     84     def __getstate__(self, *args, **kwargs): # real signature unknown
     85         pass
     86 
     87     def __init__(self, *args, **kwargs): # real signature unknown
     88         pass
     89 
     90     @staticmethod # known case of __new__
     91     def __new__(*args, **kwargs): # real signature unknown
     92         """ Create and return a new object.  See help(type) for accurate signature. """
     93         pass
     94 
     95     def __next__(self, *args, **kwargs): # real signature unknown
     96         """ Implement next(self). """
     97         pass
     98 
     99     def __repr__(self, *args, **kwargs): # real signature unknown
    100         """ Return repr(self). """
    101         pass
    102 
    103     buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    104 
    105     closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    106 
    107     encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    108 
    109     errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    110 
    111     line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    112 
    113     name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    114 
    115     newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    116 
    117     _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    118 
    119     _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    120 
    121 3.x
    3.x

    三、管理上下文

    为了避免打开文件后忘记关闭,可以通过管理上下文,即:

    1 with open('log','r') as f:
    2          
    3     ...

    如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

    在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:

    1 with open('log1') as obj1, open('log2') as obj2:
    2     pass
    1 ###### 从一文件挨行读取并写入二文件 #########
    2  
    3 with open('test.log','r') as obj1 , open('test1.log','w') as obj2:
    4     for line in obj1:
    5         obj2.write(line)

      

  • 相关阅读:
    博客园首页CSS模板
    style、currentStyle、getComputedStyle的区别和用法
    createDocumentFragment创建文档碎片节点
    setTimeout里如果有$(this),$(this)指的是谁?
    让ie也兼容placeholder
    eval()函数可以把一个字符串当作一个JavaScript表达式一样去执行它
    遮罩层特效(根据鼠标进入离开方向出现)
    jquery之attr和prop区别
    js封装类简单举例
    自动换行 word-break:break-all和word-wrap:break-word
  • 原文地址:https://www.cnblogs.com/sunkai1993/p/6119959.html
Copyright © 2011-2022 走看看