my python day4

一、文件处理

文件处理主要分为3个部分 

        1.打开文件,得到一个文件句柄并赋给一个变量

       2.通过文件句柄对文件进行操作

       3.关闭文件

      

1 f = open("info.txt","r",encoding="utf-8")  #打开文件获得文件句柄
2 data = f.read()  #读取文件内容
3 print(data)
4 f.close(). #关闭文件

1 with open("info.txt","r",encoding="utf-8") as f:
2     data = f.read()
3     print(data)

打开文件的模式

1. 只读 (r) 默认

1 f = open("info.txt","r",encoding="utf-8") 

2.只写(w)

1 f = open("info.txt","w",encoding="utf-8")  #只写模式打开文件获得文件句柄

3.追加(a)

f = open("info.txt","a",encoding="utf-8")  #追加模式打开文件获得文件句柄

4.字节(b)

#字节形式不需要指定编码 
1
f = open("info.txt","rb") #字节形式读 2 f = open("info.txt","wb") #字节形式写 3 f = open("info.txt","ab") #字节形式追加

5.读写(r+)

1 f = open("info.txt","r+",encoding="utf-8")  #读写模式打开文件获得文件句柄

6.写读(w+)

f = open("info.txt","w+",encoding="utf-8")  #写读打开文件获得文件句柄

7.追加读写(a+)

f = open("info.txt","a+",encoding="utf-8")  #追加读写打开文件获得文件句柄

8.文件的操作

 1 d1= f.read()  #读取文件所有内容
 2 d2 = f.read(3) #读取文件3个字符
 3 d3 = f.readlines()  #读取所有内容,并以列表的形式展示出来
 4 d4 = f.readline()  #读取文件的一行内容
 5 d5 = f.readable()  #文件是否可读
 6 f.close()
 7 f = open("info2.txt","w",encoding="utf-8")
 8 f.write("444
")  #写入内容
 9 f.writable()  #是否可写
10 f.writelines(["555"])  #以列表的形式写入内容
11 f.close()
12 f = open("info.txt2","wb")
13 f.write("ddd
".encode("utf-8"))
14 f.writelines(["666".encode("utf-8")])
15 print(f.writable())  #是否可写
16 # f.close()
17 print(f.name)  #文件名
18 f.mode  #文件打开模式
19 f.closed  #文件是否关闭
20 f.flush() #刷新缓存
21 open("info.txt","rb")
22 f.seek(6) #从文件开头移动6个字节位置
23 print(f.tell()) #光标所在位置
24 f.seek(2,1)# 相对于上一次光标位置移动
25 print(f.tell())
26 f.seek(-2,2)
27 print(f.tell())  #从文件末尾移动光标位置
28 f =open("info.txt","r+",encoding="utf-8")
29 f.truncate(10)  #truncate截断属于写操作  #不能用w,w+模式打开
30 f.close()
31 #文件没有修改这一说话,只有覆盖
32 with open("info.txt","r") as f,open("info3.txt","w") as f2:
33         data = f.readlines()
34         f2.write(data[1])
35 #读取文件
36 with open("info.txt","r",encoding="utf-8") as f:
37     for line in f:  #遍历文件内容
38         print(line)
View Code

二、三元表达式

age =10
res = True if age >5 else False.  #三元表达式

三、列表解析

[expression for item1 in iterable1 if condition1
r = [i for i in range(10)]  #列表解析

四、生成器表达式

r = (i for i in range(10))  #生成器表达式

五、迭代器

迭代器协议:对象必须提供一个next方法,执行该函数要么返回迭代中的下一个值,要么引起stop iteration 异常终止迭代

可迭代对象:实现迭代器协议的对象,对象内部具有__iter__方法,__next__方法。字符串、列表、元组、字典、集合、文件

简单的来说就是可以被for循环的对象。

 1 "hello".__iter__()
 2 [1,2].__iter__()
 3 (1,2,3).__iter__()
 4 {"name":"a","age":16}.__iter__()
 5 {1,2,3}.__iter__()
 6 open("info.txt","r").__iter__()
 7 #for 循环的本质  先调用__iter__方法,得到可迭代对象,再调用__next__方法,直到遇到stopiteration 
8 h1 = "hello".__iter__() 9 h1.__next__() #取值 10 l1 = [1,2].__iter__() 11 l1.__next__() #取值 12 t1 = (1,2,3).__iter__() 13 t1.__next__() #取值 14 d1 = {"name":"a","age":16}.__iter__() 15 d1.__next__() #取值 16 s1 = {1,2,3}.__iter__() 17 s1.__next__() #取值 18 f1 = open("info.txt","r").__iter__() 19 f1.__next__()
l =[1,3,2]
for i in l:
    print(i)
l = l.__iter__()
while True:
    try:
        d = l.__next__()
        print(d)
    except StopIteration:
        break

六、生成器

1.通过生成器表达式得到生成器

r = (i for i in range(10))  #生成器表达式

2.通过生成器函数得到生成器

只要函数中存在yield关键字就是生成器函数,函数名()就得到生成器,但不运行函数。next()运行函数

生成器只能遍历一次

 1 def foo():
 2     print("in the 1")
 3     yield 1
 4     print("in the 2")
 5     yield 2
 6     print("in the 3")
 7     yield 3
 8 f = foo()  #得到生成器,但不运行函数
 9 print(f)
10 r1 = f.__next__()    #运行函数 碰到yield 返回结果
11 print(r1)
12 r2 = f.__next__()
13 print(r2)

yield的作用 1. 相当于return 返回值

      2.保存函数运行状态。通过send传递值

 1 def foo():
 2     print("in the 1")
 3     r1 = yield 1   #碰到yield 得到返回值,并停到该位置
 4     print("r1的值:",r1)
 5     r2 = yield 2  #从上一次停留位置继续运行,碰到yield得到返回值,并停留该位置
 6     print("r2的值",r2)
 7     print("in the 3")
 8     yield 3
 9 f = foo()
10 f1 = next(f)
11 print(f1)
12 f2 = f.send(666)  #通过yield传值给r1继续运行
13 print(f2)
 1 #生产者消费者模型
 2 import time
 3 def cunsumer(name):
 4     print("我是%s,我准备吃包子"%name)
 5     while True:
 6         baozi = yield
 7         time.sleep(0.1)
 8         print("%s吃完了%s"%(name,baozi))
 9 def producer():
10     c1 = cunsumer("a")
11     c2 = cunsumer("b")
12     c1.__next__()
13     c2.__next__()
14     for i in range(10):
15         c1.send("肉包%s"%i)
16         c2.send("肉包%s"%i)
17 producer()
View Code

七 、装饰器

本质就是一个函数,在装饰器原则下为修饰函数添加新功能。

原则:1.不修改被修饰函数的源代码2.不修改被修饰函数的调用方式

装饰器 = 高阶函数 + 函数嵌套 + 闭包

 1 import time
 2 def timmer(func):
 3     def wrapper(*args,**kwargs):
 4         start_time = time.time()
 5         time.sleep(1)
 6         s = func(*args,**kwargs)
 7         print("s的总和为%s"%s)
 8         stop_time= time.time()
 9         print("foo运行事件%s"%(stop_time-start_time))
10         return s
11     return wrapper
12 
13 @timmer  #相当于foo = timmer(foo)
14 def foo():
15     '''计算0-10的总和'''
16     s = 0
17     for i in range(10):
18         s += i
19     return s
20 s = foo()
21 print(s)
View Code
 1 #有参数的函数
 2 import time
 3 def timmer(func):
 4     def wrapper(*args,**kwargs):
 5         start_time = time.time()
 6         time.sleep(1)
 7         s = func(*args,**kwargs)  #运行foo(l)
 8         print("s的总和为%s"%s)
 9         stop_time= time.time()
10         print("foo运行事件%s"%(stop_time-start_time))
11         return s
12     return wrapper
13 
14 @timmer  #相当于foo = timmer(foo) 等到wrapper
15 def foo(l):
16     '''计算0-10的总和'''
17     s = 0
18     for i in l:
19         s += i
20     return s
21 s = foo(range(100))。  #运行wrapper
22 print(s)
View Code
 1 usr_dict={"user":None,"login":None}
 2 user_info =[{"name":"a","pas":"1"},
 3             {"name":"b","pas":"2"},
 4             {"name":"c","pas":"3"}]
 5 def auth_type(file="tb"):
 6     def auth(func):
 7         def wrapper(*args,**kwargs):
 8             if usr_dict["user"] and usr_dict["login"]:
 9                 res = func(*args,**kwargs)
10                 return res
11             usr = input("请输入你的用户名").strip()
12             psd = input("请输入你的密码").strip()
13             if file =='tb':
14                 for info in user_info:
15                     if usr == info["name"] and psd ==info["pas"]:
16                         print("登入成功")
17                         usr_dict["user"] = usr
18                         usr_dict["login"] = True
19                         res = func(*args,**kwargs)
20                         return res
21                 else:
22                     print("用户名或密码错误")
23             else:
24                 print("不知道")
25         return wrapper
26     return auth
27 @auth_type(file="tb")
28 def home():
29     print("欢迎回家")
30 # @auth
31 # def shopper(name,food):
32 #     print("%s的购物车里有%s"%(name,food))
33 # home()
34 # shopper("a","ff")
35 home()
View Code
原文地址:https://www.cnblogs.com/Ezhizen/p/11167119.html