Python之路【第五篇】python基础 之初识函数(一)和文件管理

时间:2021-06-05 04:08:54

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

函数

一、背景                                                                                                                 

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

 while True:
if cpu利用率 > 90%:
#发送邮件提醒
连接邮箱服务器
发送邮件
关闭连接 if 硬盘使用空间 > 90%:
#发送邮件提醒
连接邮箱服务器
发送邮件
关闭连接 if 内存占用 > 80%:
#发送邮件提醒
连接邮箱服务器
发送邮件
关闭连接

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

 def 发送邮件(内容)
#发送邮件提醒
连接邮箱服务器
发送邮件
关闭连接 while True: if cpu利用率 > 90%:
发送邮件('CPU报警') if 硬盘使用空间 > 90%:
发送邮件('硬盘报警') if 内存占用 > 80%:

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

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

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

二、定义和使用                                                                              

 def 函数名(参数):

     ...
函数体
...
返回值

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

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

1、返回值

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

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

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

返回值数=0:返回None

返回值数=1:返回object

返回值数>1:返回tuple

2、参数

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

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

  • 普通参数
  • 默认参数
  • 动态参数
      • 定义函数  (形参和实参)普通参数
 # ######### 定义函数 ######### 

 # name 叫做函数func的形式参数,简称:形参
def func(name):
print(name)
)   # ######### 执行函数 #########   # 'xiaoming' 叫做函数func的实际参数,简称:实参  func('xiaoming')   普通参数
      •  默认参数
 # name 叫做函数func的形式参数,简称:形参
# def func(name, age=18): #age 是默认参数 如果下面没有指定参数,就直接用默认参数
# print("%s:%s" % (name, age))
#
#
# # 指定参数
# func('wupeiqi', 19) #19 替代了默认参数
# # 使用默认参数
# 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)
#动态参数
      • 万能参数     
 def f1(*args,**kwargs):
print(args)
print(kwargs) f1(11,22,33,44,k1='v1',k2='v2')

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

3、全局变量和局部变量

 # 全局变量 与 局部变量
# name = "lhf" #全局变量 任何位置都可以调用
# def change_name():
# name = "shuai" #局部变量
# print("change_name",name) #如果没有局部变量直接调用全局变量,如果有直接调用局部变量
# change_name()
# print(name) # globals() 关键字的用法
# name = "lhf"
# def change_name():
# global name #调用全局变量
# name = "shuai" #给全局变量赋值
# print("change_name",name)
# change_name()
# print(name) NAME = "产品经理"
def yangjiang():
#NAME = "史正文"
global NAME #已经声明,NAME 就是全局的那个变量
NAME = "小东北" #修改 全局的变量
print("我要搞",NAME)
def qupengfei():
#NAME = "基"
print("我要搞",NAME)
yangjiang()
qupengfei()
# 如果函数中没有global关键字,
# 有声明局部变量
# NAME = ["产品经理","廖博士"]
# def qupengfei():
# NAME = "myself"
# print("我要搞",NAME)
# qupengfei()
# 无声明局部变量
# NAME = ["产品经理","廖博士"]
# def qupengfei():
# #NAME = "myself"
# NAME.append("123")
# print("我要搞",NAME)
# qupengfei()
#
#
# 优先读取局部变量如果没有, 能读取全局变量,无法对全局变量重新赋值
#对于可变对象,可以对内部元素进行操作
#如果函数中有global关键字,
# 有声明局部变量
# NAME = ["产品经理","廖博士"]
# def qupengfei():
# global NAME
# NAME = "myself"
# print("我要搞",NAME)
# qupengfei()
#错误示例
# NAME = ["产品经理","廖博士"]
# def qupengfei():
# NAME = "myself"
# global NAME
# print("我要搞",NAME)
# qupengfei() # 无声明局部变量
# NAME = ["产品经理","廖波湿"]
# def qupengfei():
# global NAME
# NAME = ["阿毛"]
# NAME.append('XXOO')
# print('我要搞', NAME)
# qupengfei() # 变量本质上就是全局变量, 可能读取全局变量,可对全局变量重新赋值 # NAME = ["产品经理","廖博士"]
# def yangjiang():
# #NAME = "史正文"
# global NAME #已经声明,NAME 就是全局的那个变量
# NAME = "小东北" #修改 全局的变量
# print("我要搞",NAME)
# def qupengfei():
# #NAME = "基"
# print("我要搞",NAME)
# yangjiang()
# qupengfei()

全局变量 与 局部变

 #  函数的嵌套
# NAME = "海风"
# def huangwei():
# name = "黄威"
# print(name)
# def liuyang():
# name = "刘洋"
# print(name)
# def nulige():
# name = "胡志华"
# print(name)
# print(name)
# nulige()
# liuyang()
# print(name)
# huangwei()
# print(NAME) # name = "刚娘"
# def weihou():
# name = "陈卓"
# def weiweihou():
# nonlocal name # nanlocal ,指定上一次变量 如果没找到直接直接在往上找,不会找到全局变量
# name = "冷静"
# weiweihou()
# print(name)
# print(name)
# weihou()
# print(name)

4、递归

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

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

两个递归示例

递归特性:

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

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

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

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

递归

三、内置函数     

  Python之路【第五篇】python基础 之初识函数(一)和文件管理

 # 1. 绝对值
# i = abs(-123)
# print(i) # 2 all 循环参数,如果每个元素都为真,那么all的返回值为真
# r = all([1,2,3,True,False])
# print(r) # 3 any 循环参数,如果元素有一真,那么any的返回值为真
# i = any([None,'',{},[],(),0,1])
# print(i) #
# bin() # 二进制 0b1011 ob 代表2进制
# print(bin(11))
# oct() # 八进制
# int() # 十进制
# hex() # 十六进制 #
# bool ,判断真假,把一个对象转换成布尔值 #
# str
# list # bytes 字节
# bytearray 字节列表
# 字节和字符串之间的转换
# print(bytes("112",encoding="gbk")) #
# chr(33) # 查看ASCII 中对应的字符
# ord("t") # 查看字符对应的位置
# # ascii 一个字节,8位,2**8 ,256 # 8 做编译用,把一段字符串编译成一段可执行的代码
# compile() # 9 得到商和余数商3余1
# r = divmod(10,3)
# print(r) # 10 可以执行一个字符串形式的表达式
# ret = eval("1 + 3") # 表达式,返回值
# print(ret)
# exec 执行py代码
# evel 表达式,返回值
# compile 编译 #
# filter(函数,可迭代对象) 过滤
# def f(x):
# if x >22:
# return True
# else:
# return False
# ret = filter(f,[11,22,33,44,55])
# print(list(ret))
# ret = filter(lambda x:x>22,[11,22,33,44,55])
# print(list(ret)) # 12 map(函数,可迭代对象)
# ret = map(lambda x:x+100,[1,2,3,4,5])
# print(list(ret))
# ret = map(lambda x:x+100 if x%2 == 0 else x ,[1,2,3,4,5])
# print(list(ret)) #
# globals() # 获取所有的全局变量
# locals()
# def f1():
# name = 123
# print(locals())
# print(globals())
# f1() # 14 判断某个对象是否是某个类创建的
# li = [11,22,33]
# r = isinstance(li,list)
# print(r) # 15 创建一个可被迭代的东西
# obj = iter([11,22,33,44])
# r1 = next(obj)
# # next 调用迭代的对象的值
# print(r1) #
# max()#取最大值
# min()#取最小值 # 17 求指数2的10次方
# i = pow(2,10)
# print(i) # 18 四舍五入
# r = round(3.6)
# print(r) # 19 求和
# sum() # 20 一一对应
# zip()
# li = [11,22,33,44]
# l1 = ['a','b','c','d']
# r = zip(li,l1)
# print(list(r)) # 结果:[(11, 'a'), (22, 'b'), (33, 'c'), (44, 'd')] # 21 排序,同种类型
# li = [1,211,22,3,4]
# # print(li )
# # li.sort()
# # print(li)
#
# new_li = sorted(li)
# print(new_li)

内置函数

  注:查看详细猛击这里     

内置函数map 、  filter、reduce

1、map

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

Python之路【第五篇】python基础 之初识函数(一)和文件管理

 # num =[1,2,3,4,5,11]
# def add(x):
# return x+1
# def reduce(x):
# return x-1
# def pf(x):
# return x**2
# def map_text(func,array):
# ret = []
# for i in array:
# res = func(i) #相当于传入下面函数调用的
# ret.append(res)
# return ret
# print(map_text(add,num))
# print(map_text(reduce,num))
# print(map_text(pf,num)) # num =[1,2,3,4,5,11]
# print(map_text(lambda x:x**2,num)) ############### 终极版#############
# num =[1,2,3,4,5,11]
# def map_text(func,array): #func = lambda x:x+1 array = [1,2,3,4,5,11]
# ret = []
# for i in array:
# res = func(i) #相当于传入下面函数调用的
# ret.append(res)
# return ret
# print(map_text(lambda x:x+1,num))
# 最终版本
# num =[1,2,3,4,5,11]
# print(list(map(lambda x:x+1,num))) # 需要用list处理结果

map 实现过程

2、filter

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

Python之路【第五篇】python基础 之初识函数(一)和文件管理

 ######################## filter 用法  ################################

 # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']

 # def filter_test(array):
# ret=[]
# for p in array:
# if not p.startswith('sb'):
# ret.append(p)
# return ret
#
# res=filter_test(movie_people)
# print(res) # movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
# def sb_show(n):
# return n.endswith('sb')
#
# def filter_test(func,array):
# ret=[]
# for p in array:
# if not func(p):
# ret.append(p)
# return ret
#
# res=filter_test(sb_show,movie_people)
# print(res) #终极版本
# movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao'] # def filter_test(array):
# ret = []
# for p in array:
# if not p.startswith("sb"):
# ret.append(p)
# return ret
# print(filter_test(movie_people)) # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
# def filter_test(func,array):
# ret = []
# for p in array:
# if not func(p):
# ret.append(p)
# return ret
# print(filter_test(lambda n:n.startswith("sb"),movie_people)) # movie_people=['sb_alex','sb_wupeiqi','linhaifeng','sb_yuanhao']
# print(list(filter(lambda n:not n.startswith("sb"),movie_people))) # form functools import reduce

filter

3、reduce

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

Python之路【第五篇】python基础 之初识函数(一)和文件管理

Python之路【第五篇】python基础 之初识函数(一)和文件管理

 # form functools import reduce
# num = [1,2,3,4,5,6,100]
# res = 0
# for n in num :
# res += n
# print(res) # num = [1,2,3,4,5,6,100]
# def reduce_test(array):
# res = 0
# for n in num :
# res += n
# return res
# print(reduce_test(num)) # num = [1,2,3,100]
# def reduce_test(func,array):
# res = array.pop(0)
# for n in array :
# res = func(res,n)
# return res
# print(reduce_test(lambda x,y:x*y,num)) # from functools import reduce
# num = [1,2,3,100]
# reduce(lambda x,y:x*y,num,3)
# 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、open(文件名,模式,编码) #打开方式
# 默认是只读模式
# f = open("log",'r')
# data = f.read()
# f.closed
# print(data) # 1 只读 r
# f = open("log","r",encoding='utf-8')
# f.closed
# 2 只写 w 不可读 ;文件不存在直接创建新文件,文件存在清空文件内容
# f = open("log1",'w',encoding='utf-8')
# # f.write('123')
# f.closed
# 3 只写模式 x 不存在创建,存在报错
# f = open('log2','x',encoding='utf-8')
# f.write('hello')
# f.closed
# 4 a 追加模式 不可读,不存在创建:存在则只追加内容
# f = open('log2','a',encoding='utf-8')
# f.write('\n666')
# f.closed ##########字节方式打开 open(文件名,模式)
# 1、只读 rb
# f = open('log','rb')
# data = f.read()
# f.closed
# print(data)
# 2、只写wb
# f = open('log2','wb')
# f.write(bytes('中国',encoding='utf8')) #将字符串转换成字节
# f.closed # r/w/x/a >>> 字符串
# rb/wb/xb/ab/ >>>字节 # "+" 表示可以同时读写某个文件
#
# r+, 读写【可读,可写】
# w+,写读【可读,可写】
# x+ ,写读【可读,可写】
# a+, 写读【可读,可写】 # #### r+, 读写【可读,可写】
# w,末尾追加,指针最后
# f = open('log',"r+",encoding='utf8')
# # 光标的为0 ,起始位置
# print(f.tell()) # 查看光标的位置
# data = f.read(1)
#
# print(type(data),data)
#
# # f.write('德国人')
# print(f.tell())
#
# # f.seek(0) # 以字节来讲,移动指针的位置
#
# data = f.read()
# print(type(data),data)
# f.closed # ###w+ 先清空,在写的之后,就可以写了
# f = open("log",'w+',encoding="utf8")
# f.write('何丽丽')
# f.seek(0)
# data = f.read()
# print(data)
# f.closed #####################操作##############
# 1、
# f = open('log','r+',encoding='utf8')
# f.write('haoran')
# f.flush() #把写的内容刷到硬盘去
#
# f = open('log','a+',encoding='utf8')
# a+ 的指针的位置在最后
# f.read()
# 读取所有的内容read(1)字符 read(1) b 字节 #
# f = open('log','a+',encoding='utf8')
# f.seek(0)
# data = f.readline()
# print(data) #
# f = open('log','r+',encoding='utf8')
# print(f.tell())
# print(f.seek(8))
# # 依赖指针截取前面的位置
# f.truncate()
# f.closed

文件操作

 class file(object)
def close(self): # real signature unknown; restored from __doc__
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
""" def fileno(self): # real signature unknown; restored from __doc__
文件描述符
"""
fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read().
"""
return 0 def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区
""" flush() -> None. Flush the internal I/O buffer. """
pass def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备
""" isatty() -> true or false. True if the file is connected to a tty device. """
return False def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错
""" x.next() -> the next value, or raise StopIteration """
pass def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据
"""
read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃
""" readinto() -> Undocumented. Don't use this; it may go away. """
pass def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""
readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
"""
pass def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表
"""
readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
"""
return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""
seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
"""
pass def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置
""" tell() -> current file position, an integer (may be a long integer). """
pass def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据
"""
truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().
"""
pass def write(self, p_str): # real signature unknown; restored from __doc__
写内容
"""
write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
"""
pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""
writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
"""
pass def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部
"""
xreadlines() -> returns self. For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
"""
pass 2.x

2.x

 class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict". newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string. If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass def write(self, *args, **kwargs): # real signature unknown
写内容
pass def __getstate__(self, *args, **kwargs): # real signature unknown
pass def __init__(self, *args, **kwargs): # real signature unknown
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default 3.x

3.x

三、管理上下文

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

 with open('log','r') as f:

     ...

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

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

 with open('log1') as obj1, open('log2') as obj2:
pass
 ###### 从一文件挨行读取并写入二文件 #########

 with open('test.log','r') as obj1 , open('test1.log','w') as obj2:
for line in obj1:
obj2.write(line)