本接主要内容:

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

一。set 集合数据类型

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

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

s1 = {"","","",""}

##或者
s2 = set()
  • set 提供的功能
 class set(object):
"""
set() -> new empty set object
set(iterable) -> new set object Build an unordered collection of unique elements.
"""
def add(self, *args, **kwargs): # real signature unknown
"""
Add an element to a set,添加元素 This has no effect if the element is already present.
"""
pass def clear(self, *args, **kwargs): # real signature unknown
""" Remove all elements from this set. 清除内容"""
pass def copy(self, *args, **kwargs): # real signature unknown
""" Return a shallow copy of a set. 浅拷贝 """
pass def difference(self, *args, **kwargs): # real signature unknown
"""
Return the difference of two or more sets as a new set. A中存在,B中不存在 (i.e. all elements that are in this set but not the others.)
"""
pass def difference_update(self, *args, **kwargs): # real signature unknown
""" Remove all elements of another set from this set. 从当前集合中删除和B中相同的元素"""
pass def discard(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set if it is a member. If the element is not a member, do nothing. 移除指定元素,不存在不保错
"""
pass def intersection(self, *args, **kwargs): # real signature unknown
"""
Return the intersection of two sets as a new set. 交集 (i.e. all elements that are in both sets.)
"""
pass def intersection_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the intersection of itself and another. 取交集并更更新到A中 """
pass def isdisjoint(self, *args, **kwargs): # real signature unknown
""" Return True if two sets have a null intersection. 如果没有交集,返回True,否则返回False"""
pass def issubset(self, *args, **kwargs): # real signature unknown
""" Report whether another set contains this set. 是否是子序列"""
pass def issuperset(self, *args, **kwargs): # real signature unknown
""" Report whether this set contains another set. 是否是父序列"""
pass def pop(self, *args, **kwargs): # real signature unknown
"""
Remove and return an arbitrary set element.
Raises KeyError if the set is empty. 移除元素
"""
pass def remove(self, *args, **kwargs): # real signature unknown
"""
Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. 移除指定元素,不存在保错
"""
pass def symmetric_difference(self, *args, **kwargs): # real signature unknown
"""
Return the symmetric difference of two sets as a new set. 对称差集 (i.e. all elements that are in exactly one of the sets.)
"""
pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
""" Update a set with the symmetric difference of itself and another. 对称差集,并更新到a中 """
pass def union(self, *args, **kwargs): # real signature unknown
"""
Return the union of sets as a new set. 并集 (i.e. all elements that are in either set.)
"""
pass def update(self, *args, **kwargs): # real signature unknown
""" Update a set with the union of itself and others. 更新 """
pass

集合提供的功能总览

  • add 增加元素
#!/bin/env python

s1 = {"",""}
s1.add("")
print(s1) ##打印结果如下:
{'', '', ''} Process finished with exit code 0
  • clear 清除元素
#!/bin/env python
## s1 = {"",""}
s1.add("")
print(s1)
s1.clear()
print(s1) #显示如下
{'', '', ''}
set() #看见原先集合内的数据已经清空 Process finished with exit code 0
  • copy 集合拷贝 -- 浅拷贝
s1 = {"","","","[1,2,3,4]"}
s2 = s1.copy() print(s2) ## 显示如下
{'', '', '[1,2,3,4]', ''} 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":,
    "#2":,
    "#4":,
    } new_dic = {
    "#1":,
    "#2":,
    "#3":,
    } ##分别定义两个字典用于存放老的 新的信息
    #如下分别定义两个集合,分别存放老的插槽信息,新的插槽信息
    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': , '#2': } #删除后老字典的值 
    {'#1': , '#2': , '#3': } #增加后字典的值
    {'#1': , '#2': , '#3': }  #最后按照新的修改后的值 ###以上就完成了更新

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

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

1.自定义函数

  • 声明函数

函数的声明:

  def  空格  函数名  括号 :

    函数体

    ...

    ...

    返回值

如下例子

def name ():
print("这是一个函数") name() ##显示如下:
这是一个函数 Process finished with exit code

分别解析如下:

  • 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 ""
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 即为一个普通参数-形式参数 -- 简称为形参

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

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

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

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

def name (name,add,age,phone=11111111111):
print("你输入的名字为: %s,你的住址为: %s,你的年龄为%s, 你的手机号码为%s"%(name,add,age,phone)) name("赵文成","北京","") ##显示如下:
你输入的名字为: 赵文成,你的住址为: 北京,你的年龄为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("赵文成","北京","",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("赵文成","北京","",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="",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的方式打开的那么读取的就是一个字节

详细如下:

 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

注:

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

文成小盆友python-num3 集合,函数,-- 部分内置函数的更多相关文章

  1. python之三元表达式、列表推导、生成器表达式、递归、匿名函数、内置函数

    目录 一 三元表达式 二 列表推到 三 生成器表达式 四 递归 五 匿名函数 六 内置函数 一.三元表达式 def max(x,y): return x if x>y else y print( ...

  2. python基础12_匿名_内置函数

    一个二分查找的示例: # 二分查找 示例 data = [1, 3, 6, 7, 9, 12, 14, 16, 17, 18, 20, 21, 22, 23, 30, 32, 33, 35, 36, ...

  3. Python 入门基础12 --函数基础5 匿名函数、内置函数

    今日内容: 1.三元表达式 2.列表.元组生成式 | 字典生成式 3.递归 4.匿名函数 5.内置函数 一.三元表达式 三元运算符:就是 if...else... 语法糖 前提:if 和 else # ...

  4. python协程函数、递归、匿名函数与内置函数使用、模块与包

    目录: 协程函数(yield生成器用法二) 面向过程编程 递归 匿名函数与内置函数的使用 模块 包 常用标准模块之re(正则表达式) 一.协程函数(yield生成器用法二) 1.生成器的语句形式 a. ...

  5. python基础之函数式编程、匿名函数、内置函数

    一 函数式编程 不修改外部状态. 模仿数学里得函数进行编程. 用函数编程写出得代码相当精简. 可读性比较差. 例子: y=2*x+1 x=1 def test(x): return 2*x+1 tes ...

  6. python递归-三元表达式-列表生成式-字典生成式-匿名函数-部分内置函数-04

    递归 递归: # 函数在调用阶段直接或间接地又调用了自身 应用场景: # 将列表中的数字依次打印出来(循环的层数是你必须要考虑的点)   -->  l = [1, [2, [3, [4, [5, ...

  7. Python学习(八) —— 内置函数和匿名函数

    一.递归函数 定义:在一个函数里调用这个函数本身 递归的最大深度:997 def func(n): print(n) n += 1 func(n) func(1) 测试递归最大深度 import sy ...

  8. 【python】dir(__builtins__)查看python中所用BIF(内置函数)

    dir(__builtins__)查看python中所用BIF(内置函数)

  9. 查看python内部模块命令,内置函数,查看python已经安装的模块命令

    查看python内部模块命令,内置函数,查看python已经安装的模块命令 可以用dir(modules) 或者用 pip list或者用 help('modules') 或者用 python -m  ...

  10. python基础知识15---三元表达式、列表推导式、生成器表达式、递归、匿名函数、内置函数

    阅读目录 一 三元表达式.列表推导式.生成器表达式 二 递归与二分法 三 匿名函数 四 内置函数 五 阶段性练习 一. 三元表达式.列表推导式.生成器表达式 1 三元表达式 name=input('姓 ...

随机推荐

  1. [布局]bootstrap基本标签总结2

    缩略图 <div class="container"> <div class="row"> <div class="co ...

  2. Qt之QTableView显示富文本(使用了QAbstractTextDocumentLayout和QTextDocument)

    http://blog.csdn.net/liang19890820/article/details/50973099

  3. 【HDOJ】1500 Chopsticks

    DP. #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm ...

  4. 计算新浪Weibo消息长度

    此文为计算新浪Weibo的消息长度的方法. 就是 (发言请遵守社区公约,还可以输入119字). var getMessageLength = (function() { var byteLength ...

  5. HDOJ 1302(UVa 573) The Snail(蜗牛爬井)

    Problem Description A snail is at the bottom of a 6-foot well and wants to climb to the top. The sna ...

  6. VS013的单元测试去哪里了

    需要安装这个插件 http://visualstudiogallery.msdn.microsoft.com/45208924-e7b0-45df-8cff-165b505a38d7

  7. Codeforces Round #236 (Div. 2)E. Strictly Positive Matrix(402E)

    E. Strictly Positive Matrix   You have matrix a of size n × n. Let's number the rows of the matrix f ...

  8. puppet aix package 之rsync安装

    AIX中使用RPM安装RSync遇到的问题及解决办法 最近在折腾AIX的系统,它里面本来有一个包管理工具叫installp,但是俺不会用,也不知道从那里找包. 幸亏AIX提供了RPM的支持,所以安装软 ...

  9. HER COFFEE夜场代金券【1折】_北京美食团购_360团购导航

    HER COFFEE夜场代金券[1折]_北京美食团购_360团购导航 HER COFFEE夜场代金券

  10. Java Hibernate 主键生成10大策略

    本文将介绍Hibernate中主键生成的几种策略方案,有需要的朋友可以参考一下. 1.自动增长identity 适用于MySQL.DB2.MS SQL Server,采用数据库生成的主键,用于为lon ...