python学习之路基础篇(三)
博客参考:http://www.cnblogs.com/wupeiqi/articles/4943406.html
http://www.cnblogs.com/luotianshuai/p/4949497.html
一、简单回顾上次课程内容
主要内容:str|list|dict 类---对象
具体内容可以参考:
http://www.cnblogs.com/wupeiqi/articles/5433925.html
http://www.cnblogs.com/wupeiqi/articles/5444685.html
二、python后续学习方法:首先整理课程讲解内容到博客,然后再写作业
三、本次课程内容
1.数据类型-set
小结:
列表和集合set的区别(小知识点):
列表:有序 可重复 可嵌套
集合set:无序 不重复的序列
集合set的引入:
列表的创建
方法一:list((1,2,3))
方法二:list1 = (1,2,3,4)
同理,集合set的创建也有两种方法
主要从两个方面来进行集合set的学习
1.1 如何创建集合set
方法一:s = {1,2,3,4}
方法二:list1 = [1,2,3,4]
s1 = set{list1}
小知识点:空集合 s2 = {}
s = {1,2,3} print(s,type(s)) list1 = [1,2,3,4] s1 = set(list1) print(s1,type(s1)) s2 = set() print(s2,type(s2))
程序运行结果如下:
{1, 2, 3} <class 'set'> {1, 2, 3, 4} <class 'set'> set() <class 'set'>
1.2操作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 """ 此处假定两个集合A,B,difference:删除A中存在B中不存在的元素 S = A.difference(B),此操作不改变A,B两个集合的内容""" """ Return the difference of two or more sets as a new set. (i.e. all elements that are in this set but not the others.) """ pass def difference_update(self, *args, **kwargs): # real signature unknown """ 此处假定两个集合A,B,difference:删除A中存在B中不存在的元素 S = A.difference(B),此操作会改变A集合的内容""" """ Remove all elements of another set from this set. """ 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 """将AB两个集合中都存在的元素组成一个新的集合,此操作不会改变集合AB的内容""" """ 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 """将AB两个集合中都存在的元素组成一个新的集合,此操作会更新A或者是集合B A.intersection_update(B),则将AB集合中都存在的元素来更新集合A,反之更新集合B""" """ Update a set with the intersection of itself and another. """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ 假定两个集合A、B,如果两个集合的交集为空则返回为真""" """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ 假定两个集合A、B,集合A的每一个元素是否都在包含集合B中 A.issubset(B)""" """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ 假定两个集合A、B,集合B的每一个元素是否都在集合A A.issuperset(B)""" """ 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 """假定AB两个集合,将A中存在B中不存在的元素和在B中存在和A中不存在的元素作为一个新的集合, 这个操作不会影响集合AB的内容""" """ 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 """假定AB两个集合,将A中存在B中不存在的元素和在B中存在和A中不存在的元素作为一个集合, 去更新集合A或者B,这个操作会影响集合A、B的内容""" """ Update a set with the symmetric difference of itself and another. """ pass def union(self, *args, **kwargs): # real signature unknown """两个集合AB,将A和B的并集作为新集合的元素,也即新集合中的元素要么在集合A中,要么在集合B中""" """ 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 """更新集合,使用集合AB的并集来更新集合""" """ Update a set with the union of itself and others. """ pass def __and__(self, *args, **kwargs): # real signature unknown """ Return self&value. """ pass def __contains__(self, y): # real signature unknown; restored from __doc__ """ x.__contains__(y) <==> y in x. """ pass def __eq__(self, *args, **kwargs): # real signature unknown """ Return self==value. """ pass def __getattribute__(self, *args, **kwargs): # real signature unknown """ Return getattr(self, name). """ pass def __ge__(self, *args, **kwargs): # real signature unknown """ Return self>=value. """ pass def __gt__(self, *args, **kwargs): # real signature unknown """ Return self>value. """ pass def __iand__(self, *args, **kwargs): # real signature unknown """ Return self&=value. """ pass def __init__(self, seq=()): # known special case of set.__init__ """ set() -> new empty set object set(iterable) -> new set object Build an unordered collection of unique elements. # (copied from class doc) """ pass def __ior__(self, *args, **kwargs): # real signature unknown """ Return self|=value. """ pass def __isub__(self, *args, **kwargs): # real signature unknown """ Return self-=value. """ pass def __iter__(self, *args, **kwargs): # real signature unknown """ Implement iter(self). """ pass def __ixor__(self, *args, **kwargs): # real signature unknown """ Return self^=value. """ pass def __len__(self, *args, **kwargs): # real signature unknown """ Return len(self). """ pass def __le__(self, *args, **kwargs): # real signature unknown """ Return self<=value. """ pass def __lt__(self, *args, **kwargs): # real signature unknown """ Return self<value. """ 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 __ne__(self, *args, **kwargs): # real signature unknown """ Return self!=value. """ pass def __or__(self, *args, **kwargs): # real signature unknown """ Return self|value. """ pass def __rand__(self, *args, **kwargs): # real signature unknown """ Return value&self. """ pass def __reduce__(self, *args, **kwargs): # real signature unknown """ Return state information for pickling. """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass def __ror__(self, *args, **kwargs): # real signature unknown """ Return value|self. """ pass def __rsub__(self, *args, **kwargs): # real signature unknown """ Return value-self. """ pass def __rxor__(self, *args, **kwargs): # real signature unknown """ Return value^self. """ pass def __sizeof__(self): # real signature unknown; restored from __doc__ """ S.__sizeof__() -> size of S in memory, in bytes """ pass def __sub__(self, *args, **kwargs): # real signature unknown """ Return self-value. """ pass def __xor__(self, *args, **kwargs): # real signature unknown """ Return self^value. """ pass __hash__ = None
补充说明:带双下划线的都有特殊含义
li = [11,22,33] __init__
li() __call__
li[0] __getitem__
li[0] = 123 __setitem__
del li[0] __delitem__
操作集合的具体实例如下:
1.集合add的使用 s1 = {11,22,33,44,55,} s1.add(123) print(s1) 程序运行结果如下: {33, 11, 44, 22, 55, 123} 2.集合difference的使用 s1 = {11,22,33,44,55,} s2 = {11,22,33,44,} s = s1.difference(s2) print(s) print(s1) print(s2) 程序运行结果如下: {55} {33, 11, 44, 22, 55} {33, 11, 44, 22} 从输出结果可以看出difference不会修改s1 s2集合本身 3.集合difference_update的使用 s1 = {11,22,33,44,55} s2 = {11,22,33,44} s3 = s1.difference_update(s2) print(s3) print(s1) print(s2) 程序运行结果如下: None {55} {33, 11, 44, 22} 从输出结果可以看出集合s1已经被修改 4.集合discard的使用 discard:删除集合中指定的元素 s1 = {11,22,33,44,55} s1.discard(11) print(s1) 程序运行结果如下: {22,33,44,55} 第二种情况:移除集合中不存在的元素(即便元素不存在也不会报错) s1 = {11,22,33,44,55,} s1.discard(88) print(s1) 程序运行结果如下: {33, 11, 44, 22, 55} 5.集合clear的使用 clear:清空集合中所有的元素 s1 = {11,22,33,44,55,} s1.clear() print(s1) 程序运行结果如下: set() 6.集合pop的使用 s1 = {11,22,33,44,55,} s1.pop() print(s1) 程序运行结果如下: {11, 44, 22, 55} 7.集合remove的使用 s1 = {11,22,33,44,55,} s1.remove(44) print(s1) 程序运行结果如下: {33, 11, 22, 55} 如果元素不在集合中,则会报错 s1 = {11,22,33,44,55,} s1.remove(66) print(s1) 报错信息如下 Traceback (most recent call last): File "D:/PythonS13/day3/test.py", line 34, in <module> s1.remove(66) KeyError: 66 8.集合intersection的使用 s1 = {11,22,33,44,55} s2 = {11,22,33,44} s3 = s1.intersection(s2) print(s3) 程序运行结果如下: {33, 11, 44, 22} 9.集合intersection_update的使用 s1 = {11,22,33,44,55} s2 = {11,22,33,44} s1.intersection_update(s2) print(s1) 10.集合isdisjoint的使用 s1 = {11,22,33,44,55} s2 = {11,22,33,44} s3 = {66,77,88} s4 = s1.isdisjoint(s2) s5 = s1.isdisjoint(s3) print(s4) print(s5) 程序运行结果如下: False True 11.集合issubset和issuperset的使用 s1 = {11,22,33,44,55} s2 = {11,22,33,44} s3 = {66,77,88} s4 = s2.issubset(s1) s5 = s1.issuperset(s2) print(s4) print(s5) 程序运行结果如下: True True
集合的典型应用:CMDB中资产采集
具体需求: old_dict = { "#1":8, "#2":4, "#4":2, } new_dict = { "#1":4, "#2":4, "#3":2, } renew_dict = { "#1":4, "#2":4, "#3":2, } #应该删除哪几个槽位 #应该更新哪几个槽位 #应该增加哪几个槽位
大体思路:
1.应该删除哪几个槽位:old中存在的new不存在 old.difference(new) 2.应该更新哪几个槽位:new中存在old中不存在 new.difference(old) 3.应该增加哪几个槽位:old和new中都存在 old.intersection(new) old: #1 #2 #4 new: #1 #2 #3 第一步:将#4去除 #1 #2 #3(2G) #1 #2 #3 第二步:更新#1 1.old_dict存在,new不存在 old_keys = old_dict.keys() new_keys = new_dict.keys() old_set = set(old_keys) new_set = set(new_keys) remove_set = old_set.difference(new_set) 2.new中存在,old中不存在 remove_set = new_set.difference(old_set) 3.new和old中都存在 update_set = old_set.intersection(new_set)
代码的具体实现如下:
old_keys = old_dict.keys() old_set = set(old_keys) new_keys = new_dict.keys() new_set = set(new_keys) print(new_set) print(old_set) remove_set = old_set.difference(new_set) add_set = new_set.difference(old_set) update_set = new_set.intersection(old_set) print(remove_set) print(add_set) print(update_set)
2.函数
函数的分类
1.面向过程:根据业务逻辑从上向下进行代码的编写,从而实现功能
2.函数式编程:把需求理解为一个大的功能块,然后将其进行拆分成一个一个的小功能模块,从而实现全部的功能
面向过程的缺点: 1.代码的可读性差 2.代码的可重用性差 函数式编程的优点: 1.将实现某一个功能的代码段封装到函数中,日后无需重复编写 2.使得程序的扩展性和功能的重用性更好
2.1 自定义函数
在学习函数之前,一直是使用面向过程编程,即根据业务逻辑从上向下进行编写从而实现功能,在开发过程中实现重复功能的时候最常见的就是进行代码的复制和粘贴
,也就是将之前实现的代码块复制到现在需要实现功能的位置。
while True: if cpu利用率 > 90%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 if 硬盘使用空间 > 90%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 if 内存占用 > 80%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接
上面的代码就是使用面向过程来实现的,如果报警比较多的话就会进行N多次的复制和粘贴,怎么才能简化这个操作呢,看下面的代码:
def 发送邮件(内容) #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 while True: if cpu利用率 > 90%: 发送邮件('CPU报警') if 硬盘使用空间 > 90%: 发送邮件('硬盘报警') if 内存占用 > 80%:
很明显,上面的代码可读性更好,而且代码的重用性也得到了很好的体现。
面向过程和函数式编程的区别: 面向过程:根据需求一行一行写代码,逻辑混乱并且代码重复,不易修改且代码重用性差 函数式编程:将功能封装到函数中,以后无需重复编写,需要时进行调用函数 面向对象:对函数进行分类和封装,尽可能降低代码的耦合性,使得代码的扩展性更好
2.2 函数式编程
函数式编程最重要的是增强代码的重用性和可读性
def 函数名(参数): ... 函数体 ...
函数的定义主要有如下要点:
- def:表示函数的关键字
- 函数名:函数的名称,以后使用函数时根据函数名调用函数
- 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
- 参数:为函数体提供数据
- 返回值:当函数执行完毕后,可以给调用者返回数据。
1、返回值return
函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。
def 发送短信(): 发送短信的代码... if 发送成功: return True else: return False while True: # 每次执行发送短信函数,都会将返回值自动赋值给result # 之后,可以根据result来写日志,或重发等操作 result = 发送短信() if result == False: 记录日志,短信发送失败...
2、参数
为什么要有参数?看下下面的例子:
如果不定义参数,用函数的话:(每个有相同功能的都写个函数,说好的代码简化呢?)
def CPU报警邮件() #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 def 硬盘报警邮件() #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 def 内存报警邮件() #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 while True: if cpu利用率 > 90%: CPU报警邮件() if 硬盘使用空间 > 90%: 硬盘报警邮件() if 内存占用 > 80%: 内存报警邮件()
使用函数:(代码明显少了很多,把重复的内用改为参数调用!)
def 发送邮件(邮件内容) #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 while True: if cpu利用率 > 90%: 发送邮件("CPU报警了。") if 硬盘使用空间 > 90%: 发送邮件("硬盘报警了。") if 内存占用 > 80%: 发送邮件("内存报警了。")
2.3 函数的有四种不同的参数:
1.普通参数
2.默认参数
3.指定参数
4.动态参数
1.普通参数
# ######### 定义函数 ######### # name 叫做函数func的形式参数,简称:形参 def func(name): print(name) # ######### 执行函数 ######### # 'xingcan' 叫做函数func的实际参数,简称:实参 func('xingcan')
但是普通参数有个问题!你在定义参数的时候定义了几个参数,你在调用的时候必须给他几个参数否则就报错!
def func(name,age): print(name,age) func('parameter1') #报错内容:TypeError: func() takes exactly 2 arguments (1 given)
2.默认参数:
在没有给指定参数传递实参时他就会使用参数的默认值
def func(name, age = 18):
print("%s:%s" %(name,age))
func('liyuemei')
func('liyuemei',19)
# 指定参数 func('liyuemei', 19) # 使用默认参数 func('liyuemei')
程序输出结果如下:
liyuemei:18 liyuemei:19
注:默认参数需要放在参数列表最后,要不就会报错!原因是:他的参数赋值是一个一个的赋值。
3.指定参数
指定参数:即指定将实参赋值给哪个形参,此时可以不按照顺序来写
def send(xxoo,content,xx='hello world'): print(xxoo,content,xx) print('邮件发送成功',xxoo,content) return True while True: em = input('请输入邮箱地址:') #result = send(em,'sb',) result = send(em,xx='sb',content='OK') if result == True: print('发送成功') else: print('发送失败')
程序执行结果如下:
请输入邮箱地址:lmyxztjob@126.com lmyxztjob@126.com OK sb 邮件发送成功 lmyxztjob@126.com OK 发送成功
动态参数:
动态参数顾名思义就是可以动态的去扩展函数参数的数量!
例子:1 (多个单个变量,整合成元组)
def f1(*args): print(args,type(args)) f1(11) f1([1,2,3,4,]) l1 = [1,2,3,4,4,5,6] f1(l1) f1(*l1) str1 = 'alex' f1(str1) f1(*str1)
程序执行结果如下:
(11,) <class 'tuple'> ([1, 2, 3, 4],) <class 'tuple'> ([1, 2, 3, 4, 4, 5, 6],) <class 'tuple'> (1, 2, 3, 4, 4, 5, 6) <class 'tuple'> ('alex',) <class 'tuple'> ('a', 'l', 'e', 'x') <class 'tuple'>
一定要注意加*和不加*的区别:
不加*,则是将整个列表作为一个元组 加*:将列表中的每一个元素都转换为元组一个元素,如果是字符串,则将单个字符转换为元组的一个元素
例子:2(整合为字典变量)
def f1(**args): print(args,type(args)) f1(n1='alex',n2=38) #{'n1': 'alex', 'n2': 38} <class 'dict'> dic = {'k1':'v1','k2':'v2'} f1(**dic)
程序执行结果如下:
{'n1': 'alex', 'n2': 38} <class 'dict'> {'k2': 'v2', 'k1': 'v1'} <class 'dict'>
例子:3(整合了*args,**args)
def f1(*args,**kwargs): print(args) print(kwargs) f1(11,22,33,44,k1='v1',k2='v2',n1='www',n2='sss')
程序运行结果如下:
(11, 22, 33, 44) {'k2': 'v2', 'n2': 'sss', 'k1': 'v1', 'n1': 'www'}
例子:4(字符串的格式化 str.format)
#可变参数*的应用 s = 'I AM {0},age {1}'.format('alex',38) print(s) s2 = 'I AM {0},age {1}'.format(*['alex',18]) print(s2) #可变参数**的应用 s3 = 'I AM {name},age {age}'.format(name='alex',age=38) print(s3) dic = {'name':'alex','age':38} s4 = 'I AM {name},age {age}'.format(**dic) print(s4) #程序返回结果如下: I AM alex,age 38 I AM alex,age 18 I AM alex,age 38 I AM alex,age 38
扩展案例:发送邮件
import smtplib from email.mime.text import MIMEText from email.utils import formataddr def email(message): msg = MIMEText("邮件报警测试", 'plain', 'utf-8') msg['From'] = formataddr(["shuaige",'shuaige@test.com']) #发件人和发件邮箱 msg['To'] = formataddr(["帅哥",'451161316@qq.com']) msg['Subject'] = message #这里我调用了参数 server = smtplib.SMTP("smtp.test.com", 25) server.login("shuaige@126.com", "pwdnq.buzhidao") server.sendmail('shuaige@126.com', ['451161316@qq.com',], msg.as_string()) server.quit() if __name__ == '__main__': cpu = 100 disk = 500 ram = 50 for i in range(1): if cpu > 90: alert = 'CPU出问题了' #这里设置了一个变量 email(alert) #这里调用函数的时候引用了上面的变量,当执行函数的时候形参讲会被替换掉,message='CPU出问题了' 发送邮件! if disk > 90: alert = '硬盘出问题了' email(alert) if ram> 80: alert = '内存出问题了' email(alert)
2.3 内置参数
内置函数:python把各个模块中常用的一些方法给拿出来方便使用
>>> li = [11,22,33,44]
>>> type(li) #查看数据类型
<type 'list'>
>>> dir(list) #查看类型包含的那些方法
>>>help(list) #查看类型中包含的方法的详细说明
内置函数的使用
n = abs(-1) #求绝对值
print(n)
#0,None,"",[],{},():False
print(all([1,2,3,4])) #每个元素都为真结果才为真
print(all([1,2,3,0]))
print(any([1,2,3,0])) #有一个元素为真返回结果就为真
print(bin(5)) #把十进制数字转换为二进制
print(oct(5)) #把十进制数字转换为八进制
print(hex(5)) #把十进制数字转换为十六进制
print(bool(0)) #布尔值,返回结果为False或者是True
print(bool(1)) #
程序运行结果如下:
1
True
False
True
0b101
0o5
0x5
False
True
2.4 函数的作用域
def say(): name = "mohan" print(name) say() 这个输出: mohan # 是没有问题的,那么看下下面的例子: def say(): name = "mohan" print(name) say() print name # 这个能不能调用呢,不能,会报错!函数的作用域就是在函数里定义的变量不能被外面使用!
接着看下面这个例子
name2 = "mohan" def say(): name = "yamei" print name print name2 say() 输出结果: yamei mohan
问题:我在外面定义的全局变量在函数内可以改他吗? #看下面的例子:
name2 = "meinv"
def say():
name = "hanyue"
name2 = "hanyue is meinv"
print(name,name2)
say()
print(name2)
#输出结果:
hanyue hanyue is meinv #在函数内改变了
meinv #但是外面调用还是没有改变!
但我就是想在函数里改变全局变量是否可以呢?可以!
#但是我就想在函数内改掉这个变量怎么办呢?在函数内调用global参数!(提供这个功能,但是不建议用!你在局部变量改全局变量很容易引起混乱)
name2 = "meinv" def say(): global name2 name = "hanyue" name2 = "hanyue is meinv" print(name,name2) say() print(name2)
输出结果:
hanyue hanyue is meinv hanyue is meinv
提示:列表/字典也可以是全局变量
name = [11,22,33,44] def f1(): age = 18 name.append('100') print(age,name) def f2(): age = 20 print(age,name) f1() f2() print(name) 程序运行结果如下: 18 [11, 22, 33, 44, '100'] 20 [11, 22, 33, 44, '100'] [11, 22, 33, 44, '100']
2.5 return参数
def count(): for i in range(1,10): if i = 5: return else: print i print "Hello World" #所以当i=5的时候就直接跳出了函数了,这里是不会被打印出来了!不是循环!!! count() 输出结果: 1 2 3 4
return 一般写在函数的末尾,一般你想看函数的执行结果!然后判断后面的程序。看下面的例子
def count(): name = "mohan" for i in range(1,10): if i == 5: print "hello" else: print i return name #在这里加了一个return user = count() if user == "mohan": #然后判断,看下执行结果! print "oh mohan is coming" 执行结果: 1 2 3 4 hello 6 7 8 9 oh mohan is coming #这里看下! 上面的判断执行了!所以return这个把name的值输出了!
2.6 函数的补充内容
1.猜猜看下面的返回值是多少
def f1(a1,a2): return a1 + a2 def f1(a1,a2): return a1 * a2 ret = f1(8,8) print(ret) #程序的运行结果:64
2.python函数传递的是引用还是值
#python函数传递的是引用
def f1(a1):
a1.append(100)
li = [11,22,33,44,]
f1(li)
print(li)
程序的运行结果:[11, 22, 33, 44, 100]
从输出的结果来看,li的值已经被修改,这说明python传递参数时
传递的是引用,而不是具体的值,如果是值,则li的值应该是不变的,
即还是[11,22,33,44,],a1的值则为[11,22,33,44,100]
三、文件操作
对于文件的操作主要从三个方面来说明:
1.打开文件
文件句柄 = file('文件路径', '模式') #python中打开文件有两种方式,即:open(...) 和 file(...) ,本质上前者在内部会调用后者来进行文件操作,推荐使用 open(),python2,open()和file()可以正常使用,python3.0以后file方法讲被用做其他,open方法会自动的去帮你找他调用得方法在那里!
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。 打开文件的模式有: r,只读模式(默认)。 w,只写模式。【不可读;不存在则创建;存在则删除内容;】 a,追加模式。【可读; 不存在则创建;存在则只追加内容;】 "+" 表示可以同时读写某个文件 r+,可读写文件。【可读;可写;可追加】 w+,无意义 a+,同a "U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用) rU r+U "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注) rb wb ab
2.操作文件
f.read()
read()#无参数,读取全部,有参数 b按照字节,无b按照字符
tell():获取当前指针位置
seek():跳转到指定位置
write():写数据
close():关闭文件
fileno():文件描述符
flush():把写入的内容强制刷新到磁盘上
readable():是否可读
readline():仅读取一行
seekable():是否可移动
truncate():截取数据,指针位置之后的全部清空
readlines():for循环文件句柄 f = open(xxxx)
for line in f:
print(line)
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 0 (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
3.with
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
with open('log','r') as f: ...
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass
例子:比如要修改nginx.conf 文件然后还需要回滚怎么做?
with open('nginx.conf','r') as obj1,open('nginx.conf.new','w') as obj2: for i in obj1.readlines(): i = i.strip() print i obj2.write(i) obj2.write('\n') #读取nginx.conf每行然后存储到新的文件nginx.conf.new里!