博客参考老师文章:http://www.cnblogs.com/wupeiqi/
博客参考老师文章:http://www.cnblogs.com/luotianshuai/p/4949497.html
上节回顾:
str:字符串
strs = "rain,sunny,ray,wind"
list:列表
lists = ['rain','sunny','ray','wind']
tuple:元组
tuples = ('rain','sunny','ray','wind')
dict:字典
dicts = {'name':'rain','age':21}
今日知识:
一、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 """
11 Add an element to a set.
12
13 This has no effect if the element is already present.
14 """
15 pass
16
17 def clear(self, *args, **kwargs): # real signature unknown
18 """ Remove all elements from this set. """
19 pass
20
21 def copy(self, *args, **kwargs): # real signature unknown
22 """ Return a shallow copy of a set. """
23 pass
24
25 def difference(self, *args, **kwargs): # real signature unknown
26 """
27 Return the difference of two or more sets as a new set.
28
29 (i.e. all elements that are in this set but not the others.)
30 """
31 pass
32
33 def difference_update(self, *args, **kwargs): # real signature unknown
34 """ 删除当前set中的所有包含在 new set 里的元素 """
35 """ Remove all elements of another set from this set. """
36 pass
37
38 def discard(self, *args, **kwargs): # real signature unknown
39 """ 移除元素 """
40 """
41 Remove an element from a set if it is a member.
42
43 If the element is not a member, do nothing.
44 """
45 pass
46
47 def intersection(self, *args, **kwargs): # real signature unknown
48 """ 取交集,新创建一个set """
49 """
50 Return the intersection of two or more sets as a new set.
51
52 (i.e. elements that are common to all of the sets.)
53 """
54 pass
55
56 def intersection_update(self, *args, **kwargs): # real signature unknown
57 """ 取交集,修改原来set """
58 """ Update a set with the intersection of itself and another. """
59 pass
60
61 def isdisjoint(self, *args, **kwargs): # real signature unknown
62 """ 如果没有交集,返回true """
63 """ Return True if two sets have a null intersection. """
64 pass
65
66 def issubset(self, *args, **kwargs): # real signature unknown
67 """ 是否是子集 """
68 """ Report whether another set contains this set. """
69 pass
70
71 def issuperset(self, *args, **kwargs): # real signature unknown
72 """ 是否是父集 """
73 """ Report whether this set contains another set. """
74 pass
75
76 def pop(self, *args, **kwargs): # real signature unknown
77 """ 移除 """
78 """
79 Remove and return an arbitrary set element.
80 Raises KeyError if the set is empty.
81 """
82 pass
83
84 def remove(self, *args, **kwargs): # real signature unknown
85 """ 移除 """
86 """
87 Remove an element from a set; it must be a member.
88
89 If the element is not a member, raise a KeyError.
90 """
91 pass
92
93 def symmetric_difference(self, *args, **kwargs): # real signature unknown
94 """ 差集,创建新对象"""
95 """
96 Return the symmetric difference of two sets as a new set.
97
98 (i.e. all elements that are in exactly one of the sets.)
99 """
100 pass
101
102 def symmetric_difference_update(self, *args, **kwargs): # real signature unknown
103 """ 差集,改变原来 """
104 """ Update a set with the symmetric difference of itself and another. """
105 pass
106
107 def union(self, *args, **kwargs): # real signature unknown
108 """ 并集 """
109 """
110 Return the union of sets as a new set.
111
112 (i.e. all elements that are in either set.)
113 """
114 pass
115
116 def update(self, *args, **kwargs): # real signature unknown
117 """ 更新 """
118 """ Update a set with the union of itself and others. """
119 pass
120
121 def __and__(self, y): # real signature unknown; restored from __doc__
122 """ x.__and__(y) <==> x&y """
123 pass
124
125 def __cmp__(self, y): # real signature unknown; restored from __doc__
126 """ x.__cmp__(y) <==> cmp(x,y) """
127 pass
128
129 def __contains__(self, y): # real signature unknown; restored from __doc__
130 """ x.__contains__(y) <==> y in x. """
131 pass
132
133 def __eq__(self, y): # real signature unknown; restored from __doc__
134 """ x.__eq__(y) <==> x==y """
135 pass
136
137 def __getattribute__(self, name): # real signature unknown; restored from __doc__
138 """ x.__getattribute__('name') <==> x.name """
139 pass
140
141 def __ge__(self, y): # real signature unknown; restored from __doc__
142 """ x.__ge__(y) <==> x>=y """
143 pass
144
145 def __gt__(self, y): # real signature unknown; restored from __doc__
146 """ x.__gt__(y) <==> x>y """
147 pass
148
149 def __iand__(self, y): # real signature unknown; restored from __doc__
150 """ x.__iand__(y) <==> x&=y """
151 pass
152
153 def __init__(self, seq=()): # known special case of set.__init__
154 """
155 set() -> new empty set object
156 set(iterable) -> new set object
157
158 Build an unordered collection of unique elements.
159 # (copied from class doc)
160 """
161 pass
162
163 def __ior__(self, y): # real signature unknown; restored from __doc__
164 """ x.__ior__(y) <==> x|=y """
165 pass
166
167 def __isub__(self, y): # real signature unknown; restored from __doc__
168 """ x.__isub__(y) <==> x-=y """
169 pass
170
171 def __iter__(self): # real signature unknown; restored from __doc__
172 """ x.__iter__() <==> iter(x) """
173 pass
174
175 def __ixor__(self, y): # real signature unknown; restored from __doc__
176 """ x.__ixor__(y) <==> x^=y """
177 pass
178
179 def __len__(self): # real signature unknown; restored from __doc__
180 """ x.__len__() <==> len(x) """
181 pass
182
183 def __le__(self, y): # real signature unknown; restored from __doc__
184 """ x.__le__(y) <==> x<=y """
185 pass
186
187 def __lt__(self, y): # real signature unknown; restored from __doc__
188 """ x.__lt__(y) <==> x<y """
189 pass
190
191 @staticmethod # known case of __new__
192 def __new__(S, *more): # real signature unknown; restored from __doc__
193 """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
194 pass
195
196 def __ne__(self, y): # real signature unknown; restored from __doc__
197 """ x.__ne__(y) <==> x!=y """
198 pass
199
200 def __or__(self, y): # real signature unknown; restored from __doc__
201 """ x.__or__(y) <==> x|y """
202 pass
203
204 def __rand__(self, y): # real signature unknown; restored from __doc__
205 """ x.__rand__(y) <==> y&x """
206 pass
207
208 def __reduce__(self, *args, **kwargs): # real signature unknown
209 """ Return state information for pickling. """
210 pass
211
212 def __repr__(self): # real signature unknown; restored from __doc__
213 """ x.__repr__() <==> repr(x) """
214 pass
215
216 def __ror__(self, y): # real signature unknown; restored from __doc__
217 """ x.__ror__(y) <==> y|x """
218 pass
219
220 def __rsub__(self, y): # real signature unknown; restored from __doc__
221 """ x.__rsub__(y) <==> y-x """
222 pass
223
224 def __rxor__(self, y): # real signature unknown; restored from __doc__
225 """ x.__rxor__(y) <==> y^x """
226 pass
227
228 def __sizeof__(self): # real signature unknown; restored from __doc__
229 """ S.__sizeof__() -> size of S in memory, in bytes """
230 pass
231
232 def __sub__(self, y): # real signature unknown; restored from __doc__
233 """ x.__sub__(y) <==> x-y """
234 pass
235
236 def __xor__(self, y): # real signature unknown; restored from __doc__
237 """ x.__xor__(y) <==> x^y """
238 pass
239
240 __hash__ = None
241
242 set
1.1 创建set集合
s = set() set1 = set(['rain','sunny','ray','wind']) print(set1) #{'wind', 'ray', 'sunny', 'rain'}
1)创建一个空集合
s = set() set1 = set(['rain','sunny','ray','wind']) print(set1) #{'wind', 'ray', 'sunny', 'rain'}
2)将一个list转换成set(其它类型相同方法)
lists = ['rain','sunny','ray','wind'] set1 = set(lists) print(set1) #{'ray', 'wind', 'rain', 'sunny'}
1.2 set常用的集合方法
1)add 增加一个元素
s = set() s.add('rain') print (s) # {'rain'}
2)clear 清除所有的元素
s.clear() print(s) # set()
3)difference 判断元素不相同的
set1 = { 'rain', 'ray', 'wind'} set2 = {'sunny', 'rain', 'wind'} #判断元素不相同的(不改变原数据,新建一个集合保存差异数据set3) set3 = set1.difference(set2) #set1中存在,set2中不存在的打印 print(set3) # {'ray'} set3 = set2.difference(set1) print(set3) # {'sunny'}
4)symmetric_difference 差集
set1 = { 'rain', 'ray', 'wind'} set2 = {'sunny', 'rain', 'wind'} #对称差集(不改变原数据,新建一个集合保存差异数据set3) set3 = set1.symmetric_difference(set2) print(set3) #{'ray', 'sunny'}
5)difference_update 差集取数据 ,更新数据
set1 = { 'rain', 'ray', 'wind'} set2 = {'sunny', 'rain', 'wind'} #更新set1数据(改变原数据) set1.difference_update(set2) #先做difference比较,然后拿到比较后的结果,更新到set1 print(set1)
6)sysmmetric_difference_update
set1 = { 'rain', 'ray', 'wind'} set2 = {'sunny', 'rain', 'wind'} #更新set1数据(改变原数据) set1.symmetric_difference_update(set2) #先做symmetric_difference比较,然后拿到比较后的结果,更新到set1 print(set1) #{'sunny', 'ray'}
7)discard
set1 = {11,22,33,44} #移除不存在的元素时,不会报错 set1.discard(1111) print(set1) #{33, 11, 44, 22}
8)remove
set1 = {11,22,33,44} #移除不存在的元素时,会报错
9)pop
set1 = {11,22,33,44} #移除set1中随机元素,并返回移除的值(可接收) set1.pop() print(set1) #{11, 44, 22}
10)intersection
set1 = { 'rain', 'ray', 'wind'} set2 = {'sunny', 'rain', 'wind'} #set1与set2的交集 set3 = set1.intersection(set2) print(set3) # {'rain', 'wind'}
10)intersection_updat
set1 = { 'rain', 'ray', 'wind'} set2 = {'sunny', 'rain', 'wind'} #set1与set2的交集,并且直接更新到set1 set1.intersection_update(set2) print(set1) # {'rain', 'wind'}
11)isdisjoint
set1 = { 'rain', 'ray', 'wind'} set2 = {'sunny', 'rain', 'wind'} # 如果没有交集,返回True,否则返回False print(set1.isdisjoint(set2)) # False set1 = {11,22,33,} set2 = {44,55,66,} # 如果没有交集,返回True,否则返回False print(set1.isdisjoint(set2)) #True
12)issubset
set1 = {11,22,33,} set2 = {22,33,} #判断是否为子序列 print(set2.issubset(set1)) #True print(set1.issubset(set2)) # False
13)issuperset
set1 = {11,22,33,} set2 = {22,33,} #判断是否为父序列 print(set1.issuperset(set2)) #True
14)union 并集
set1 = {11,22,33,} set2 = {22,33,} #set1与set2的并集 set3 = set1.union(set2) print(set3) #{33, 11, 22}
15)update 批量更新、添加元素
set1 = {11,22,33,} # set1.update("接收一个可以迭代的数据") set1.update('rain') print(set1) #{33, 'i', 'r', 11, 'n', 22, 'a'}
1 练习:寻找差异 2 old_dict = { 3 "#1":8, 4 "#2":4, 5 "#4":2,} 6 7 new_dict = { 8 "#1":4, 9 "#2":4, 10 "#3":2,} 11 需要删除:? 12 需要新建:? 13 需要更新:? 14 打印出更新后的old_dict
1 old_set = set(old_dict.items()) 2 new_set = set(new_dict.items()) 3 removes = old_set.difference(new_set) 4 # print(removes) 5 for a in removes: 6 if a in old_set: 7 old_set.remove(a) 8 # print(old_set) 9 adds = new_set.difference(old_set) 10 # print(adds) 11 for i in adds: 12 old_set.add(i) 13 old_dicts = dict(old_set) 14 15 print(old_dicts) 16 执行结果: 17 {'#1': 4, '#2': 4, '#3': 2}
二、函数
面向过程:
程序按顺序执行,代码一层一层堆迭
函数式:
将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可
面向对象:
对函数进行分类和封装,让开发“更快更好更强
开始函数之旅
1、先对比一段代码
面向过程的一段代码:
while True: if cpu利用率 > 90%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 if 硬盘使用空间 > 90%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 if 内存占用 > 80%: #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接
面向对象的一段代码:
def 发送邮件(内容) #发送邮件提醒 连接邮箱服务器 发送邮件 关闭连接 while True: if cpu利用率 > 90%: 发送邮件('CPU报警') if 硬盘使用空间 > 90%: 发送邮件('硬盘报警') if 内存占用 > 80%:
发送邮件('内存报警')
第二段代码利用函数将某功能代码封装到函数中,在日后便无需重复编写,仅调用函数即可
2、函数式编程
函数式编程最重要的是增强代码的重用性和可读性:
###### 定义函数 ######
def 函数名(参数): ... 函数体 ... 返回值
# 只有定义时,函数体不执行
# 被调用时才会执行
函数的定义主要有如下要点:
- def:表示函数的关键字
- 函数名:函数的名称,日后根据函数名调用函数
- 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...
- 参数:为函数体提供数据
- 返回值:当函数执行完毕后,可以给调用者返回数据。
1) 返回值
函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。
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%:
3)函数的有三中不同的参数:
- 普通参数
- 默认参数
- 动态参数
普通参数:(严格按照顺序,将实际参数赋值给形式参数)
# ######### 定义函数 ######### # name 叫做函数func的形式参数,简称:形参 def func(name): print('hello',name) # ######### 执行函数 ######### # 'rain' 叫做函数func的实际参数,简称:实参 func('rain') # #########执行结果########### hello rain
普通参数的特点:
- 定义了几个参数个数,调用时必须给定所有参数
-
def func(name,age): print('hello %s ,how old are you ? %s ' %(name,age)) func('rain') ####报错信息#### TypeError: func() missing 1 required positional argument: 'age'
####正确调用####
func('rain',21)
hello rain ,how old are you ? 21
默认参数:(必须放下参数列表的最后面)
- 当用户没有给定参数值时,直接使用默认参数,不会报错
def func(name, age = 21): print ("%s:%s" %(name,age)) # 指定参数 func('rain', 19) # rain:19 # 使用默认参数 func('rain') # rain:21
注:默认参数需要放在参数列表最后,否则就会报错!原因是:他的参数赋值是一个一个的赋值。如果提供了默认值的形参,你默认一定要往后排序为了就是你给那些没有陪默认值的参数 !
指定参数:(将实际参数给指定的形式参数)
def func(name,age=21): print('hello %s how old are you ? %s'%(name,age)) #将实际参数给指定的形式参数 func(age='rain',name=22) #打印结果 hello 22 how old are you ? rain
动态参数:
例子:1 (*args,默认将传入的参数,全部放置在元组中)
def func(*args): print(args) func(11,22,33,44,55) #输出结果:(11, 22, 33, 44, 55) #传递一个 list列表 lists = [11,22,33,44,55,66] func(lists) #输出结果:([11, 22, 33, 44, 55, 66],) func(*lists) #输出结果: (11, 22, 33, 44, 55, 66)
将接收到参数值,转换成元组中的一个元素; func(*lists) 带*可以避免成为元组中的列表元素
例子:2(**args,默认将传入的参数,全部放置在字典中)
#接收一个key:values的值 def func(**args): print(args) # 执行方式一 func(name='rain',age=21) #输出结果:{'name': 'rain', 'age': 21} # 执行方式二 dicts = {'name':'rain','age':21} func(**dicts) #输出结果:{'name': 'rain', 'age': 21}
例子:3(整合了*args,**args)
def func(*args,**kwargs): print (args) print(kwargs) func(11,22,33,44,name='rain',age=21,) #返回结果: # (11, 22, 33, 44) # {'name': 'rain', 'age': 21}
内置函数
如何查询内置函数
如何查询内置函数的使用 >>> li = [11,22,33,44] >>> type(li) #查看数据类型 <type 'list'> >>> dir(list) #查看类型包含的那些方法 >>>help(list) #查看类型中包含的方法的详细说明
#其它数据类型也使用同样的方法
三、三元运算
1 result = 值1 if 条件 else 值2
例子:
#普通代码表达式 name = input("输入用户名:") if name == 'rain': print("用户名正确") else: print("用户名不对") #三目运算 name = input("输入用户名:") print("用户名正确") if name == 'rain' else print("用户名不对")
函数的作用域
#这里的name为局部变量,所以在函数体外使用是会报"NameError"
def say(): name = "rain" print(name) say() def say(): name = "rain" print(name) say() print(name) #输出结果 #NameError: name 'name' is not defined
全局变量
#这里的name为全局变量,全局变量可以在函数体内使用,也可以在函数体外使用 name = 'rain' def say(): name2 = "sunny" print(name) #rain print(name2) #sunny say() print(name) # #rain
# 输出结果 rain sunny rain
总结:函数的作用域就是在函数里定义的变量不能被外面使用!但是外部全局定义的全局变量在函数内是可以使用的。
在外面定义的全局变量可以在函数内修改,但函数外面不生效!!!(相当于函数外直接屏蔽了函数内的所有变量)
name = 'rain' def say(): name = 'wind' name2 = "sunny" print(name) #wind(在函数内改变了) print(name2) #sunny say() print(name) #rain(但是外面调用还是没有改变)
print(name2) # NameError: name 'nam2' is not defined
如果想在函数里改变全局变量,如下:
name = 'rain' def say(): global name name = 'wind' name2 = "sunny" print(name) #wind(在函数内改变了) print(name2) #sunny say() print(name) #wind(在函数外也发生了改变)
return参数
return在这里作用为:当i=5时,中止循环
def count(): for i in range(3,10): if i = 5: return else: print i print "Hello World" #所以当i=5的时候就直接跳出了函数了,这里是不会被打印出来了!不是循环!!! count() 输出结果: 3 4 5
return在这里作用为: 利用return返回值来判断程序是否正常执行
def names(): name = input('input your name :') if name == 'rain': return True else: return False ret = names() print(ret) if ret: print("用户名正确") else: print("用户名错误") ####输出结果 input your name :rain True 用户名正确 ####输出结果 input your name :sunny False 用户名错误
四、文件操作
操作文件时,一般需要经历如下步骤:
- 打开文件
- 操作文件
1、打开文件
文件句柄 = open('文件路径', '模式')
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
2、使用方法
1 class file(object): 2 3 def close(self): # real signature unknown; restored from __doc__ 4 关闭文件 5 """ 6 close() -> None or (perhaps) an integer. Close the file. 7 8 Sets data attribute .closed to True. A closed file cannot be used for 9 further I/O operations. close() may be called more than once without 10 error. Some kinds of file objects (for example, opened by popen()) 11 may return an exit status upon closing. 12 """ 13 14 def fileno(self): # real signature unknown; restored from __doc__ 15 文件描述符 16 """ 17 fileno() -> integer "file descriptor". 18 19 This is needed for lower-level file interfaces, such os.read(). 20 """ 21 return 0 22 23 def flush(self): # real signature unknown; restored from __doc__ 24 刷新文件内部缓冲区 25 """ flush() -> None. Flush the internal I/O buffer. """ 26 pass 27 28 29 def isatty(self): # real signature unknown; restored from __doc__ 30 判断文件是否是同意tty设备 31 """ isatty() -> true or false. True if the file is connected to a tty device. """ 32 return False 33 34 35 def next(self): # real signature unknown; restored from __doc__ 36 获取下一行数据,不存在,则报错 37 """ x.next() -> the next value, or raise StopIteration """ 38 pass 39 40 def read(self, size=None): # real signature unknown; restored from __doc__ 41 读取指定字节数据 42 """ 43 read([size]) -> read at most size bytes, returned as a string. 44 45 If the size argument is negative or omitted, read until EOF is reached. 46 Notice that when in non-blocking mode, less data than what was requested 47 may be returned, even if no size parameter was given. 48 """ 49 pass 50 51 def readinto(self): # real signature unknown; restored from __doc__ 52 读取到缓冲区,不要用,将被遗弃 53 """ readinto() -> Undocumented. Don't use this; it may go away. """ 54 pass 55 56 def readline(self, size=None): # real signature unknown; restored from __doc__ 57 仅读取一行数据 58 """ 59 readline([size]) -> next line from the file, as a string. 60 61 Retain newline. A non-negative size argument limits the maximum 62 number of bytes to return (an incomplete line may be returned then). 63 Return an empty string at EOF. 64 """ 65 pass 66 67 def readlines(self, size=None): # real signature unknown; restored from __doc__ 68 读取所有数据,并根据换行保存值列表 69 """ 70 readlines([size]) -> list of strings, each a line from the file. 71 72 Call readline() repeatedly and return a list of the lines so read. 73 The optional size argument, if given, is an approximate bound on the 74 total number of bytes in the lines returned. 75 """ 76 return [] 77 78 def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 79 指定文件中指针位置 80 """ 81 seek(offset[, whence]) -> None. Move to new file position. 82 83 Argument offset is a byte count. Optional argument whence defaults to 84 (offset from start of file, offset should be >= 0); other values are 1 85 (move relative to current position, positive or negative), and 2 (move 86 relative to end of file, usually negative, although many platforms allow 87 seeking beyond the end of a file). If the file is opened in text mode, 88 only offsets returned by tell() are legal. Use of other offsets causes 89 undefined behavior. 90 Note that not all file objects are seekable. 91 """ 92 pass 93 94 def tell(self): # real signature unknown; restored from __doc__ 95 获取当前指针位置 96 """ tell() -> current file position, an integer (may be a long integer). """ 97 pass 98 99 def truncate(self, size=None): # real signature unknown; restored from __doc__ 100 截断数据,仅保留指定之前数据 101 """ 102 truncate([size]) -> None. Truncate the file to at most size bytes. 103 104 Size defaults to the current file position, as returned by tell(). 105 """ 106 pass 107 108 def write(self, p_str): # real signature unknown; restored from __doc__ 109 写内容 110 """ 111 write(str) -> None. Write string str to file. 112 113 Note that due to buffering, flush() or close() may be needed before 114 the file on disk reflects the data written. 115 """ 116 pass 117 118 def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 119 将一个字符串列表写入文件 120 """ 121 writelines(sequence_of_strings) -> None. Write the strings to the file. 122 123 Note that newlines are not added. The sequence can be any iterable object 124 producing strings. This is equivalent to calling write() for each string. 125 """ 126 pass 127 128 def xreadlines(self): # real signature unknown; restored from __doc__ 129 可用于逐行读取文件,非全部 130 """ 131 xreadlines() -> returns self. 132 133 For backward compatibility. File objects now include the performance 134 optimizations previously implemented in the xreadlines module. 135 """ 136 pass
打开文件 f = open('test.txt', 'r') # 只读 f = open('test.txt', 'w') # 只写,先清空原文件 f = open('test.txt', 'x') # 文件存在,报错;不存在,创建并只写 f = open('test.txt', 'a') # 追加 f = open('test.txt','r', encoding="utf-8") # 指定编码格式
#以写的方式打开
f = open('test.txt','w')
f.write("rain 21")
f.close()
#以追加的方式打开
f = open('test.txt','a')
f.write(' ')
f.write("sunny 22")
f.close()
#以读的方式打开
f = open('test.txt','r')
fi = f.read()
print(fi)
f.close()
#输出结果
rain 21
sunny 22
五、with方法
为了避免打开文件后忘记关闭,可以通过管理上下文,即:(建议使用此方法打开文件)
with open('文件路径', '模式') as 文件句柄: ...... ......
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
with还同时支持同时打开多个文件
with open('test.txt','r') as object1,open('test1.txt','a') as object2: for i in object1.readlines(): i=i.strip() print (i) object2.write(i) object2.write(' ') #每读一行test.txt的文件,并将读取的文件写入test1.txt中