转载请注明出处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 发送短信():

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

返回值数=0:返回None

返回值数=1:返回object

返回值数>1:返回tuple

2、参数

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

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

  • 普通参数
  • 默认参数
  • 动态参数
      • 定义函数  (形参和实参)普通参数
  1. # ######### 定义函数 #########
  2.  
  3. # name 叫做函数func的形式参数,简称:形参
  4. def func(name):
  5. print(name)
  1. # ######### 执行函数 ######### # 'xiaoming' 叫做函数func的实际参数,简称:实参 func('xiaoming') 普通参数
      •  默认参数
  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')
      • 动态参数   
  1. def func(*args):
  2. print(args)
  3. # 执行方式一
  4. func(11,33,4,4454,5)
  5. # 执行方式二
  6. li = [11,2,2,3,3,4,54]
  7. func(*li)
  8. # 动态参数
  1. def func(**kwargs):
  2. print(kwargs)
  3. # 执行方式一
  4. func(name = 'wupeiqi',age=18)
  5. # 执行方式二
  6. li = {'name':'wupeiqi', "age":18, 'gender':'male'}
  7. func(**li)
  8. #动态参数
      • 万能参数     
  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. # NAME = ["产品经理","廖博士"]
  75. # def yangjiang():
  76. # #NAME = "史正文"
  77. # global NAME #已经声明,NAME 就是全局的那个变量
  78. # NAME = "小东北" #修改 全局的变量
  79. # print("我要搞",NAME)
  80. # def qupengfei():
  81. # #NAME = "基"
  82. # print("我要搞",NAME)
  83. # yangjiang()
  84. # 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. #
  14. # bin() # 二进制 0b1011 ob 代表2进制
  15. # print(bin(11))
  16. # oct() # 八进制
  17. # int() # 十进制
  18. # hex() # 十六进制
  19.  
  20. #
  21. # bool ,判断真假,把一个对象转换成布尔值
  22.  
  23. #
  24. # str
  25. # list
  26.  
  27. # bytes 字节
  28. # bytearray 字节列表
  29. # 字节和字符串之间的转换
  30. # print(bytes("112",encoding="gbk"))
  31.  
  32. #
  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. #
  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. #
  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. #
  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. # def filter_test(array):
  6. # ret=[]
  7. # for p in array:
  8. # if not p.startswith('sb'):
  9. # ret.append(p)
  10. # return ret
  11. #
  12. # res=filter_test(movie_people)
  13. # print(res)
  14.  
  15. # movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
  16. # def sb_show(n):
  17. # return n.endswith('sb')
  18. #
  19. # def filter_test(func,array):
  20. # ret=[]
  21. # for p in array:
  22. # if not func(p):
  23. # ret.append(p)
  24. # return ret
  25. #
  26. # res=filter_test(sb_show,movie_people)
  27. # print(res)
  28.  
  29. #终极版本
  30. # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
  31.  
  32. # def filter_test(array):
  33. # ret = []
  34. # for p in array:
  35. # if not p.startswith("sb"):
  36. # ret.append(p)
  37. # return ret
  38. # print(filter_test(movie_people))
  39.  
  40. # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
  41. # def filter_test(func,array):
  42. # ret = []
  43. # for p in array:
  44. # if not func(p):
  45. # ret.append(p)
  46. # return ret
  47. # print(filter_test(lambda n:n.startswith("sb"),movie_people))
  48.  
  49. # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
  50. # print(list(filter(lambda n:not n.startswith("sb"),movie_people)))
  51.  
  52. # 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

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

文件处理

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

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

  • 打开文件
  • 操作文件

一、打开文件

       文件句柄 = 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('\n666')
  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. #
  77. # f = open('log','a+',encoding='utf8')
  78. # a+ 的指针的位置在最后
  79. # f.read()
  80. # 读取所有的内容read(1)字符 read(1) b 字节
  81.  
  82. #
  83. # f = open('log','a+',encoding='utf8')
  84. # f.seek(0)
  85. # data = f.readline()
  86. # print(data)
  87.  
  88. #
  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. def isatty(self): # real signature unknown; restored from __doc__
  28. 判断文件是否是同意tty设备
  29. """ isatty() -> true or false. True if the file is connected to a tty device. """
  30. return False
  31.  
  32. def next(self): # real signature unknown; restored from __doc__
  33. 获取下一行数据,不存在,则报错
  34. """ x.next() -> the next value, or raise StopIteration """
  35. pass
  36.  
  37. def read(self, size=None): # real signature unknown; restored from __doc__
  38. 读取指定字节数据
  39. """
  40. read([size]) -> read at most size bytes, returned as a string.
  41.  
  42. If the size argument is negative or omitted, read until EOF is reached.
  43. Notice that when in non-blocking mode, less data than what was requested
  44. may be returned, even if no size parameter was given.
  45. """
  46. pass
  47.  
  48. def readinto(self): # real signature unknown; restored from __doc__
  49. 读取到缓冲区,不要用,将被遗弃
  50. """ readinto() -> Undocumented. Don't use this; it may go away. """
  51. pass
  52.  
  53. def readline(self, size=None): # real signature unknown; restored from __doc__
  54. 仅读取一行数据
  55. """
  56. readline([size]) -> next line from the file, as a string.
  57.  
  58. Retain newline. A non-negative size argument limits the maximum
  59. number of bytes to return (an incomplete line may be returned then).
  60. Return an empty string at EOF.
  61. """
  62. pass
  63.  
  64. def readlines(self, size=None): # real signature unknown; restored from __doc__
  65. 读取所有数据,并根据换行保存值列表
  66. """
  67. readlines([size]) -> list of strings, each a line from the file.
  68.  
  69. Call readline() repeatedly and return a list of the lines so read.
  70. The optional size argument, if given, is an approximate bound on the
  71. total number of bytes in the lines returned.
  72. """
  73. return []
  74.  
  75. def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
  76. 指定文件中指针位置
  77. """
  78. seek(offset[, whence]) -> None. Move to new file position.
  79.  
  80. Argument offset is a byte count. Optional argument whence defaults to
  81. (offset from start of file, offset should be >= 0); other values are 1
  82. (move relative to current position, positive or negative), and 2 (move
  83. relative to end of file, usually negative, although many platforms allow
  84. seeking beyond the end of a file). If the file is opened in text mode,
  85. only offsets returned by tell() are legal. Use of other offsets causes
  86. undefined behavior.
  87. Note that not all file objects are seekable.
  88. """
  89. pass
  90.  
  91. def tell(self): # real signature unknown; restored from __doc__
  92. 获取当前指针位置
  93. """ tell() -> current file position, an integer (may be a long integer). """
  94. pass
  95.  
  96. def truncate(self, size=None): # real signature unknown; restored from __doc__
  97. 截断数据,仅保留指定之前数据
  98. """
  99. truncate([size]) -> None. Truncate the file to at most size bytes.
  100.  
  101. Size defaults to the current file position, as returned by tell().
  102. """
  103. pass
  104.  
  105. def write(self, p_str): # real signature unknown; restored from __doc__
  106. 写内容
  107. """
  108. write(str) -> None. Write string str to file.
  109.  
  110. Note that due to buffering, flush() or close() may be needed before
  111. the file on disk reflects the data written.
  112. """
  113. pass
  114.  
  115. def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
  116. 将一个字符串列表写入文件
  117. """
  118. writelines(sequence_of_strings) -> None. Write the strings to the file.
  119.  
  120. Note that newlines are not added. The sequence can be any iterable object
  121. producing strings. This is equivalent to calling write() for each string.
  122. """
  123. pass
  124.  
  125. def xreadlines(self): # real signature unknown; restored from __doc__
  126. 可用于逐行读取文件,非全部
  127. """
  128. xreadlines() -> returns self.
  129.  
  130. For backward compatibility. File objects now include the performance
  131. optimizations previously implemented in the xreadlines module.
  132. """
  133. pass
  134.  
  135. 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. '\n', '\r', and '\r\n'. 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 '\n', '\r', or '\r\n', and
  17. these are translated into '\n' 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 '\n' characters written are
  24. translated to the system default line separator, os.linesep. If
  25. newline is '' or '\n', no translation takes place. If newline is any
  26. of the other legal values, any '\n' 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)

  

Python之路【第五篇】python基础 之初识函数(一)和文件管理的更多相关文章

  1. Python之路(第五篇) Python基本数据类型集合、格式化、函数

    一.变量总结 1.1 变量定义 记录某种状态或者数值,并用某个名称代表这个数值或状态. 1.2 变量在内存中的表现形式 Python 中一切皆为对象,数字是对象,列表是对象,函数也是对象,任何东西都是 ...

  2. python之路第五篇之模块和加密算法(进阶篇:续)

    模块 Python中,如果要引用一些内置的函数,该怎么处理呢?在Python中有一个概念叫做模块(module) 简单地说,模块就是一个保存了Python代码的文件. 模块分类: 1)内置模块 2)自 ...

  3. Python之路(第七篇)Python作用域、匿名函数、函数式编程、map函数、filter函数、reduce函数

    一.作用域 return 可以返回任意值例子 def test1(): print("test1") def test(): print("test") ret ...

  4. 【Python之路】特别篇--Python装饰器

    前情提要 1. 作用域 在python中,函数会创建一个新的作用域.python开发者可能会说函数有自己的命名空间,差不多一个意思.这意味着在函数内部碰到一个变量的时候函数会优先在自己的命名空间里面去 ...

  5. 【Python之路】第九篇--Python基础之线程、进程和协程

    进程与线程之间的关系 线程是属于进程的,线程运行在进程空间内,同一进程所产生的线程共享同一内存空间,当进程退出时该进程所产生的线程都会被强制退出并清除.线程可与属于同一进程的其它线程共享进程所拥有的全 ...

  6. python之路第五篇之装饰器:(进阶篇)

    装饰器: 学前必备知识: def f1(): print "f1" f1() #表示函数执行 f1 #表示函数,指向内存地址 f1 = lambda x: x + 1 f1() # ...

  7. Python之路第五天,基础(6)-模块

    模块 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个 ...

  8. Python之路第五天,基础(5)-序列化和字符串格式化

    序列化 Python中用于序列化的两个模块 json 用于『字符串』和『python基本数据类型』间进行转换 pickle 用于『python特有的类型』和『python基本数据类型』间进行转换 js ...

  9. python之路第五篇之递归(进阶篇:续:经典例子剖析)

    递归 在函数内部,可以调用其他函数; 如果一个函数在内部调用自身本身,这个函数就是递归函数. 例如,我们来计算阶乘: n! = 1 x 2 x 3 x ... x n, 用函数f1(n)表示,可以看出 ...

  10. python之路第四篇(基础篇)

    一.冒泡算法实现: 方法一: li = [13,33,12,80,66,1] print li for m in range(4): num1 = li[m] num2 = li[m+1] if nu ...

随机推荐

  1. linux系统的初化始配置(包括网络,主机名,关闭firewalld与selinux)

    每次我们使用Linux都会对系统进行初始化的配置,下面我们一一列出来. 1.服务的开启 systemctl enable firewalld.service //将指定的服务设置为开机启动 syste ...

  2. gulp学习-gulpfile

    安装gulp 假设已经安装了node 和npm (淘宝的cnpm很适合国内使用). 1.首页全局安装gulp. 1 npm install --global gulp 2.其次局部安装gulp.(注: ...

  3. JavaScript常用字符串操作方法总结

    1.判断是否为字符串:typeof() var str = 'abcd'; typeof(str);   //string 2.获取字符串的长度:length var str = '123456789 ...

  4. SQL Server数据阻塞原因

    阻塞形成原因 是由于SQL Server是高并发的,同一时间会有很多用户访问,为了保证数据一致性和数据安全,引入了锁的机制.同一时间只有拿到钥匙的用户能够访问,而其他用户需要等待. 死锁形成四大必要条 ...

  5. Jmeter发送Java请求

    1.创建一个Java工程 2.把Jmeter的lib\ext目录下的ApacheJMeter_java.jar.ApacheJMeter_core.jar文件添加进该项目的Build Path 3.创 ...

  6. 文件上传之 HttpPostedFile

    HttpPostedFile类,提供对客户端已上载的单独文件的访问. 公共属性如下: SaveAs()方法,用于保存上传文件的内容. 用法为: #region 文件上传 /// <summary ...

  7. 我的基于asp.net mvc5 +mysql+dapper+easyui 的Web开发框架(1)数据库访问(0)

    一.数据库访问 概述 1. 数据库使用mysql,orm采用dapper框架.dapper框架应用简单,只是需要自己手写sql语句,但是对于像我这样写了多年sql语句的人来说,这应该不算问题,个人还是 ...

  8. TFS源代码管理的8大注意事项

    TFS源代码管理的8大注意事项 目录 源代码管理的8大注意事项... 1 1. 使用TFS进行源代码管理... 2 2. 如果代码没放在源代码管理软件里,等于它不存在... 2 3. 要早提交,常提交 ...

  9. 分割一个表到多个实体<EntityFramework6.0>

    声明方式 public class Photograph { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public in ...

  10. ng1.3+表单验证<AngularJs>

    前一篇文章说过,ng1.3+以后对于表单验证有了优化,它不再需要一个详细的表达式状态创建元素显示或隐藏. 例如:我们在ng1.3之前的版本都需要如下写法: <div class="er ...