文成小盆友python-num3 集合,函数,-- 部分内置函数

本接主要内容:

  • set -- 集合数据类型
  • 函数
  1.   自定义函数
  2.   部分内置函数

一。set 集合数据类型

set集合,是一个无序且不重复的元素集合

  • 集合基本特性
    1.     无序
    2.     不重复
  • 创建集合
#!/bin/env python

s1 = {"1","2","3","4"}

##或者
s2 = set()   
  • set 提供的功能
  1 class set(object):
  2     """
  3     set() -> new empty set object
  4     set(iterable) -> new set object
  5      
  6     Build an unordered collection of unique elements.
  7     """
  8     def add(self, *args, **kwargs): # real signature unknown
  9         """
 10         Add an element to a set,添加元素
 11          
 12         This has no effect if the element is already present.
 13         """
 14         pass
 15  
 16     def clear(self, *args, **kwargs): # real signature unknown
 17         """ Remove all elements from this set. 清除内容"""
 18         pass
 19  
 20     def copy(self, *args, **kwargs): # real signature unknown
 21         """ Return a shallow copy of a set. 浅拷贝  """
 22         pass
 23  
 24     def difference(self, *args, **kwargs): # real signature unknown
 25         """
 26         Return the difference of two or more sets as a new set. A中存在,B中不存在
 27          
 28         (i.e. all elements that are in this set but not the others.)
 29         """
 30         pass
 31  
 32     def difference_update(self, *args, **kwargs): # real signature unknown
 33         """ Remove all elements of another set from this set.  从当前集合中删除和B中相同的元素"""
 34         pass
 35  
 36     def discard(self, *args, **kwargs): # real signature unknown
 37         """
 38         Remove an element from a set if it is a member.
 39          
 40         If the element is not a member, do nothing. 移除指定元素,不存在不保错
 41         """
 42         pass
 43  
 44     def intersection(self, *args, **kwargs): # real signature unknown
 45         """
 46         Return the intersection of two sets as a new set. 交集
 47          
 48         (i.e. all elements that are in both sets.)
 49         """
 50         pass
 51  
 52     def intersection_update(self, *args, **kwargs): # real signature unknown
 53         """ Update a set with the intersection of itself and another.  取交集并更更新到A中 """
 54         pass
 55  
 56     def isdisjoint(self, *args, **kwargs): # real signature unknown
 57         """ Return True if two sets have a null intersection.  如果没有交集,返回True,否则返回False"""
 58         pass
 59  
 60     def issubset(self, *args, **kwargs): # real signature unknown
 61         """ Report whether another set contains this set.  是否是子序列"""
 62         pass
 63  
 64     def issuperset(self, *args, **kwargs): # real signature unknown
 65         """ Report whether this set contains another set. 是否是父序列"""
 66         pass
 67  
 68     def pop(self, *args, **kwargs): # real signature unknown
 69         """
 70         Remove and return an arbitrary set element.
 71         Raises KeyError if the set is empty. 移除元素
 72         """
 73         pass
 74  
 75     def remove(self, *args, **kwargs): # real signature unknown
 76         """
 77         Remove an element from a set; it must be a member.
 78          
 79         If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
 80         """
 81         pass
 82  
 83     def symmetric_difference(self, *args, **kwargs): # real signature unknown
 84         """
 85         Return the symmetric difference of two sets as a new set.  对称差集
 86          
 87         (i.e. all elements that are in exactly one of the sets.)
 88         """
 89         pass
 90  
 91     def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
 92         """ Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
 93         pass
 94  
 95     def union(self, *args, **kwargs): # real signature unknown
 96         """
 97         Return the union of sets as a new set.  并集
 98          
 99         (i.e. all elements that are in either set.)
100         """
101         pass
102  
103     def update(self, *args, **kwargs): # real signature unknown
104         """ Update a set with the union of itself and others. 更新 """
105         pass
集合提供的功能总览
  • add 增加元素
#!/bin/env python

s1 = {"1","2"}
s1.add("234")
print(s1)

##打印结果如下:
{'234', '2', '1'}

Process finished with exit code 0
  • clear 清除元素
#!/bin/env python
##


s1 = {"1","2"}
s1.add("234")
print(s1)
s1.clear()
print(s1)

#显示如下
{'234', '1', '2'}
set()               #看见原先集合内的数据已经清空

Process finished with exit code 0
  • copy 集合拷贝 -- 浅拷贝
s1 = {"1","2","123","[1,2,3,4]"}
s2 = s1.copy()

print(s2)

## 显示如下
{'2', '1', '[1,2,3,4]', '123'}

Process finished with exit code 0
  • difference 方法

  如下使用,表示为s1中存在但是s2中没有的元素

s1 = {1,2,3}
s2 = {2,3,4}
s3 = s1.difference(s2)
print(s3)

##打印如下:
{1}

Process finished with exit code 0
  • symmetric_difference

如下使用为 s1中存在但是s2中不存在的元素  + s2中存在但是s1中不存在的元素

s1 = {1,2,3}
s2 = {2,3,4}
s3 = s1.difference(s2)
print(s3)

s4 = s1.symmetric_difference(s2)
print(s4)

##显示如下:
{1}
{1, 4}

Process finished with exit code 0
  • difference_update 
s1 = {1,2,3}
s2 = {2,3,4}
s1.difference_update(s2)
print(s1)

##显示 如下:
{1}

Process finished with exit code 0

##跟difference不同之处在于update会改变原先的集合(直接更新)
  • discard

  删除指定的元素,定指定的元素不存在时不报错(比较常用的一种删除方式)


s1 = {1,2,3}
s1.discard(1)
s1.discard(123) #此元素不存在 但是依然能够执行不报错

print(s1)
##显示如下: {2, 3} Process finished with exit code 0
  • pop 

移除某个元素随机的,不常用,并且会返回这个移除的值

s1 = {1,2,3}
s2 = s1.pop()

print(s1)
print(s2,type(s2))

#显示如下:
{2, 3}
1 <class 'int'>

Process finished with exit code 0

##################################
s1 = {"sdfjsd",2,3}
s2 = s1.pop()

print(s1)
print(s2,type(s2))

#显示如下
{2, 3}
sdfjsd <class 'str'>

Process finished with exit code 0
  • remove

  当remove掉存在的元素时会报错

s1 = {"sdfjsd",2,3}

s1.remove(2)
print(s1)

#显示如下
{'sdfjsd', 3}   ##存在的元素并没有报错

Process finished with exit code 0

####
s1 = {"sdfjsd",2,3}

s1.remove(13)
print(s1)

#显示如下
Traceback (most recent call last):
  File "D:/oldboy/projects/s13/day3/sendmail.py", line 146, in <module>
    s1.remove(13)
KeyError: 13

Process finished with exit code 1

##由上可见 remove不存在的元素会导致执行失败
  • intersection
  • intersection_update   ---同样的改变原来集合

  取得两个集合的交集

s1={1,2,3,4}
s2={2,3,4,5}
s3=s1.intersection(s2)
print(s3)

##显示如下
{2, 3, 4}

Process finished with exit code 0
  • union

  取得两个元素的并集

s1={1,2,3,4}
s2={2,3,4,5}
s3=s1.union(s2)
print(s3)

#显示如下:
{1, 2, 3, 4, 5}

Process finished with exit code 0
  • update

  update()中的元素为可迭代的元素 如:字符串可迭代  列表可迭代 元组可迭代,显示如下

s1={1,2,3,4}
s1.update(["e",5,6,7,"dd",("d",12)])
print(s1)

#显示如下:
{1, 2, 3, 4, 5, 6, 7, ('d', 12), 'dd', 'e'}

Process finished with exit code 0

 

set集合应用练习:

应用需求大致如下:

模拟cmdb中资源管理情况下内存变化的探测

如下个字典中存放的分别为老的内存情况和新的内存情况,其中 #1 --代表物理的内存插槽的编号,后面的数值代表内存的大小

old_dic = {
    "#1":8,
    "#2":16,
    "#4":2,
}

new_dic = {
    "#1":8,
    "#2":4,
    "#3":2,
}

需求为根据新的字典中的内容将最新的一个字典获取到

  • 思路

分别定义两个集合一个存放老的插槽信息s1,一个存放新的插槽信息s2

然后通过几个的方法找到需要删除的插槽  找到需要增加的 再找出有可能需要更新的

  • 分析

需要删除的为s1中存在但是s2中不存在的

应该增加的是s2中有但是s1没有的

需啊更新的为,s2中存在s1中也存在但是s1中的这个值和s2中的这个值不同,以s2中的这个值来作为最新更新

  • 具体实现如下
    old_dic = {
        "#1":8,
        "#2":16,
        "#4":2,
    }
    
    new_dic = {
        "#1":8,
        "#2":4,
        "#3":2,
    }                                   ##分别定义两个字典用于存放老的 新的信息
    #如下分别定义两个集合,分别存放老的插槽信息,新的插槽信息
    old_set = set(old_dic.keys())
    new_set = set(new_dic.keys())       
    
    print(old_set)
    print(new_set)
    
    ##需要删除的
    del_set = old_set.difference(new_set)
    print(del_set)
    ##需要增加的
    add_set = new_set.difference(old_set)
    print(add_set)
    
    ##有可能需要更新的
    update_set = old_set.intersection(new_set)
    print(update_set)
    
    
    ###操作字典将老的中的删除掉
    for i in del_set:
        del old_dic[i]
    print(old_dic)
    
    #需要增加的,将老的增加上
    for i in add_set:
        old_dic[i] = new_dic[i]
    print(old_dic)
    
    #需要更新的:
    for i in update_set:
        if old_dic[i] != new_dic[i]:
            old_dic[i] = new_dic[i]
            print(old_dic)
    
    
    ###如此打印结果如下:
    {'#4', '#1', '#2'}   ##老的集合
    {'#3', '#1', '#2'}   ##新的集合
    {'#4'}       #需要删除的     
    {'#3'}   #需要增减
    {'#1', '#2'} #有可能需要修改的
    {'#1': 8, '#2': 16} #删除后老字典的值 
    {'#1': 8, '#2': 16, '#3': 2} #增加后字典的值
    {'#1': 8, '#2': 4, '#3': 2}  #最后按照新的修改后的值
    
    ###以上就完成了更新
    
    
        

二.python中的函数--懒惰即美德 

  有了函数之后就不必反反复复的向计算机传递同样的指令了。增强了代码的可读性和代码的重复利用性。

1.自定义函数

  • 声明函数

函数的声明:

  def  空格  函数名  括号 :

    函数体

    ...

    ...

    返回值

如下例子

def name ():
    print("这是一个函数")

name()

##显示如下:
这是一个函数

Process finished with exit code 0

分别解析如下:

  • 1.def --- 为函数关键字
  • 2.name  --- 函数的名称日后根据函数名调用函数 
  • 3.()   --- 固定格式(括号内可以填参数)-参数是为函数体提供数据
  • 4.print("这是一个函数")  ---函数体:具体的此函数的内容
  • 5.函数 还有返回值 ---可以给调用者返回数据, python的函数中如果不设定函数的返回 值则默认返回 True or Flse 。

小例子 :定义 一个发邮件函数,当掉用时直接给指定的地址发送邮件:

#!/bin/env python


def sendmail ():
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText('邮件内容', 'plain', 'utf-8')
    msg['From'] = formataddr(["武沛齐", 'wptawy@126.com'])
    msg['To'] = formataddr(["走人", '424662508@qq.com'])
    msg['Subject'] = "主题"

    server = smtplib.SMTP("smtp.126.com", 25)
    server.login("wptawy@126.com", "***此处填写密码***")
    server.sendmail('wptawy@126.com', ['1175677897@qq.com', ], msg.as_string())
    server.quit()

sendmail()
  • 有函数的python程序执行顺序:

  当刚开始定义 一个 函数时,并不会 执行函数体中的内容,只有在调用时才会再执行函数体中的内容。

  如下例子:

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
print("首先执行")                         
def f1 ():
    print("这是一个函数1")
def f1 ():
    print("这是一个函数2")

f1()


##打印结果
首先执行
这是一个函数2

Process finished with exit code 0

##定义第二个f1的 函数时会把之前的f1的函数覆盖掉
  • 关于函数的return

在函数中一旦执行return,函数执行过程立即终止

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def f1 ():
    print("这是一个函数1")
    return "123456"
    print("我将不会 得到执行")
result = f1()  ##将函数体中return的值赋值给 result
print(result)

###显示如下
这是一个函数1
123456

Process finished with exit code 0
  • 函数的参数

使用参数的好处是,更大话的提高了代码的可利用性,针对不同处调用参数时传不同的参数值即可如下简单的例子

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def name (name):
    print("你输入的名字为: %s"%name)

name("赵文成")

如上:函数名后面括号中的name为参数 称为形式参数

函数中参数的类型:

      • 普通参数
      • 默认参数
      • 指定参数
      • 动态参数
      • “万能参数”
  •  普通参数

如上一个例子中name 即为一个普通参数-形式参数 -- 简称为形参 

在掉用参数时传递的内容“赵文成”则为实际参数 -- 简称为实参

如下例子中说明多个普通参数当传递时是一一对应的:

 1 # -*- coding:utf-8 -*-
 2 # Author:wencheng.zhao
 3 def name (name,add,age):
 4     print("你输入的名字为: %s,你的住址为: %s,你的年龄为%s"%(name,add,age))
 5 
 6 
 7 name("赵文成","北京","26")
 8 
 9 ##显示如下:
10 你输入的名字为: 赵文成,你的住址为: 北京,你的年龄为26
11 
12 Process finished with exit code 0
  • 默认参数

默认参数是在普通参数处设定一个默认值,注意必须将默认参数设置到普通参数的后面:

def name (name,add,age,phone=11111111111):
    print("你输入的名字为: %s,你的住址为: %s,你的年龄为%s, 你的手机号码为%s"%(name,add,age,phone))


name("赵文成","北京","26")

##显示如下:
你输入的名字为: 赵文成,你的住址为: 北京,你的年龄为26, 你的手机号码为11111111111

Process finished with exit code 0

###如上在调用时没有传递参数则函数体中的值为默认值!!!!
###如下也 可以在调用时传递参数,这函数体中以传递的参数为准
# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def name (name,add,age,phone=11111111111):
    print("你输入的名字为: %s,你的住址为: %s,你的年龄为%s, 你的手机号码为%s"%(name,add,age,phone))


name("赵文成","北京","26",22222222222)

##显示如下:
你输入的名字为: 赵文成,你的住址为: 北京,你的年龄为26, 你的手机号码为22222222222

Process finished with exit code 0

当默认参数在普通参数前时就会报错:

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def name (phone=11111111111 name,add,age,):
    print("你输入的名字为: %s,你的住址为: %s,你的年龄为%s, 你的手机号码为%s"%(name,add,age,phone))


name("赵文成","北京","26",22222222222)

##报错内容如下:
  File "D:/oldboy/projects/s13/day3/temp.py", line 3
    def name (phone=11111111111 name,add,age,):
                                   ^
SyntaxError: invalid syntax

Process finished with exit code 1
  • 指定参数  

指定参数其实就是在调用普通的参数时指定普通参数的值,如果指定值则调用时传递的参数顺序没有限制

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def name (name,add,age):
    print("你输入的名字为: %s,你的住址为: %s,你的年龄为%s"%(name,add,age))


name(age="26",add="北京",name="赵文成")

##显示如下
你输入的名字为: 赵文成,你的住址为: 北京,你的年龄为26

Process finished with exit code 0
  •    动态参数1   一个星号  *
# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def name(*args):
    print(args)

name(1,2,3,4,5,6)

##显示如下:
(1, 2, 3, 4, 5, 6)

Process finished with exit code 0

调用时传递参数时*也会起到作用如下:

没有*好直接调用时则认为调用的为一个参数,带上*则会遍历所传的参数中的所有值(前提也是可迭代,字符串,列表 ,元组等)具体操作如下:

并且单个 * 默认放到元组中(双个星会默认放到字典中)

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def name(*args):
    print(args)

li = [1,2,"ww",34,"(1,2,3)"]
name(li)
##当调用没有*时则认为是一个元素,显示如下
([1, 2, 'ww', 34, '(1,2,3)'],)

Process finished with exit code 0

####################################
#当调用时有星号时如下:
# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def name(*args):
    print(args)

li = [1,2,"ww",34,"(1,2,3)"]
name(*li)

#显示
(1, 2, 'ww', 34, '(1,2,3)')

Process finished with exit code 0

动态参数2 两个星号 *

两个* 默认会放到字典中

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def name(**args):
    print(args)

dic = {"aa":1,"bb":2,"cc":3,"dd":4}
name(name=dic)

##显示如下
{'name': {'aa': 1, 'bb': 2, 'cc': 3, 'dd': 4}}

Process finished with exit code 0

########调用时利用双 **传递参数
def name(**args):
    print(args)

dic = {"aa":1,"bb":2,"cc":3,"dd":4}
name(**dic)

##显示如下
{'bb': 2, 'aa': 1, 'dd': 4, 'cc': 3}

Process finished with exit code 0
  • 万能参数

**kwargs 必须放到 *kwargs的 后面否则会报错。 即 一个* 的在前面,两个*的在后面

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def send(*args,**kwargs):
    print(args)
    print(kwargs)

send(11,22,33,k1="v1",k2="v2",)

##显示
(11, 22, 33)
{'k1': 'v1', 'k2': 'v2'}

Process finished with exit code 0
##也可以值传递一部分参数
# -*- coding:utf-8 -*-
# Author:wencheng.zhao
def send(*args,**kwargs):
print(args)
print(kwargs)

send(k1="v1",k2="v2",)
###显示如下:

()
{'k1': 'v1', 'k2': 'v2'}

Process finished with exit code 0

 万能参数应用举例(字符串的format方法)

# -*- coding:utf-8 -*-
# Author:wencheng.zhao
s = "my name is {name},age is {age}".format(name="zhaowencheng",age=26)
print(s)

dic={"name":"zhaowencheng","age":26}
s = "my name is {name},age is {age}".format(**dic)
print(s)

#############另一种表达方法
s = "im name {0},age {1}".format("abc",18)
print(s)


list = ["abc",18]
s = "im name {0},age {1}".format(*list)
print(s)
###显示

im name abc,age 18
im name abc,age 18

Process finished with exit code 0

  • 补充函数内容
      •     函数的参数传递时传的是引用
def send1(a):
    a.append(999)

a = [1,2,3,4,5]
send1(a)

print(a)

##显示如下:
[1, 2, 3, 4, 5, 999]

Process finished with exit code 0
      •         函数的全局和局部变量

全局变量:每个单独函数中都可以使用

    所有的作用域都是可读的(不一定可写)

    对应全局变量中再单个函数中的修改只能对本函数有效(除非+global)

    如果想赋值或者修改的话,必须加global

    特殊的::如列表  局部都可以读,局部也可以append,但是局部不能够重新赋值

      •     定义全局变量时建议使用全部大写

 

  • 编写带函数的python规范:

规范为声明多个函数和一个main函数,最后调用main的函数大致如下:

#!/bin/env python

NAME = "aaa"
ADFFD = "bbbb"    #全局变量声明

def fun1():
    xxxxx
    xxxxx


def fun2():
    xxxxx
    xxxxx

def fun3():
    xxxxx
    xxxxx

.
.
.


def main():
    xxxxx
    xxxxx

main()

 

三.三元运算,lambda表达式

  • 三元运算

对于简单的if else运算可以用三元运算

#!/bin/env python

if 1==1:
    name = "zhaowencheng"
else:
    name = "abc"

print(name)

name = "zhaowencheng" if 1==1 else "abc"
print(name)

##显示如下:
zhaowencheng
zhaowencheng

Process finished with exit code 0
  • lambda表达式

对于简单的函数也存在一种方便的表达方式

#!/bin/env python

def fun (a,b):
    return a + b + 100

result = fun(100,100)
print(result)

fun1 = lambda a,b : a + b + 100

result = fun1(100,100)
print(result)

####显示如下
300
300

Process finished with exit code 0

四.部分内置函数

  • abs()   --- 取得绝对值
#!/bin/env python

a = -1
print(a)
b = abs(a)
print(b)

#显示如下
-1
1

Process finished with exit code 0
  • all()  ---括号内的元素全部为真则返回True
#!/bin/env python
n = all([1,2,3,4,])
print(n)
n = all([1,2,3,4,False])
print(n)
n = all([1,"",3,4,])
print(n)
n = all([1,2,None,4,])
print(n)

##显示如下:
True
False
False
False

Process finished with exit code 0
  • any()
#!/bin/env python 
n = any([1,2,3,4,])
print(n)
n = any([1,2,3,4,False])
print(n)
n = any([1,"",3,4,])
print(n)
n = any([1,2,None,4,])
print(n)

##显示如下:
True
True
True
True

Process finished with exit code 0
  • bin() -- 把十进制转换成二进制
  • oct() -- 把十进制转换成八进制
  • hex()-- 把十进制转换成十六进制
#!/bin/env python
a = 100
print(bin(a))
print(oct(a))
print(hex(a))

##显示如下
0b1100100
0o144
0x64

Process finished with exit code 0
  • bytes()  -- 将字符串类型转换成字节类型
#!/bin/env/python 

s = "hello abc"
b = bytes(s,encoding="utf-8")
print(s,type(s))
print(b,type(b))

##显示如下
hello abc <class 'str'>
b'hello abc' <class 'bytes'>

Process finished with exit code 0

#############################################将字节类型反编译成字符串类型 ##

str(bytes(s,encoding="utf-8"),encoding="ust-8") 

 

  • open() 内置文件处理函数

文件操作主要分三个部分  打开文件   操作文件    关闭文件

  1.打开文件:

  open   r   只读

      w   只写

      x    如果当文件存在就报错,如果问价不存在就创建文件然后写内容

      a     追加

    以上模式读到的都是字符串python默认已经将二进制文件进行了处理  b 模式指的是用二进制的模式来直接操作读取操作。

      +    即可读又可写同时读写某个文件

        seek()  --调整指针的位置 --以字节的方式读取

      tell()     --取出当前指针的位置

      read()   --如果打开的方式不是以“b”的方式打开的那么读取的是一个字符。 如果是以b的方式打开的那么读取的就是一个字节

 详细如下:

  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
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

注:

  for 循环文件对象 f  循环他的时候就是循环每一行

posted @ 2016-05-24 22:53  文成小盆友  阅读(399)  评论(0编辑  收藏  举报