python基础整理笔记(四)
一. python 打开文件的方法
1. python中使用open函数打开文件,需要设定的参数包括文件的路径和打开的模式。示例如下:
1 f = open('a.txt', 'r+')
2. f为打开文件的句柄,具体读取文件的操作需要调用f的方法,示例如下:
1 f = open('a.txt', 'r+') 2 3 # read 以字符串形式打开整个文件 4 f.read() 5 6 # readline 每次只读取一行的内容,到下一次时才加载下一次 7 l = f.readline() 8 print(l) 9 while l: 10 f.readline() 11 print(l) 12 13 14 # readlines 读取所有行以列表形式返回 15 for i in f. readlines(): 16 print(i)
此外上述三个方法都有一个可选参数,是一个int类型的,限制读取内容最大size的。如果需要读取的内容很大,则只能使用readline方法一点点读取。
3. 其实打开文件的句柄本身也是可以迭代的,示例如下:
1 f = open('a.txt', 'r+') 2 # f也是每次只读取一行的内容,不过f是可以直接循环迭代的 3 for i in f: 4 print(i)
4. 写文件的函数包括write和writelines,区别为前者入参是一个str,后者为列表,示例如下:
1 f = open('a.txt', 'w+') 2 3 # write是把入参的字符整个原样写入文件的 4 f.write('saff1\nwqwq') 5 6 # 注意writelines写入列表时候不会在每个元素后面加上换行, 7 # 写到文件里以后是会连起来的,要换行需要自己加 8 l = ['1', '2', '3'] 9 f.writelines(l) 10 11 f.writelines(['%s\n'%i for i in l])
5. 使用文件结束后需要把文件句柄关闭,示例如下:
1 f = open('a.txt', 'w+') 2 f.close()
6. 如果使用with来打开文件,则不需要close了,关于文件操作的打开关闭已经直接封装好了,示例如下:
1 with open('a.txt', 'r+') as f: 2 print(f.read())
7. 整理打开的模式如下:

二. python一些内置函数整理

详细的官网文档链接 https://docs.python.org/3/library/functions.html
三. 装饰器
装饰器实际是一种接受函数作为参数的函数的语法糖。
1. 最普通的装饰器示例如下:
1 # 修饰不需要入参的函数 2 def deco(func): 3 def _deco(): 4 print("before myfunc()") 5 res = func() 6 print(" after myfunc()") 7 return res 8 return _deco 9 10 @deco 11 def myfunc(): 12 print(" myfunc() start") 13 return True 14 15 16 # 修饰有入参的函数 17 def deco2(func): 18 def _deco(a, b): 19 print("before myfunc()") 20 res = func(a, b) 21 print(" after myfunc()") 22 return res 23 return _deco 24 25 @deco2 26 def myfunc2(): 27 print(" myfunc() start") 28 print(a, b) 29 return True
2. 修饰参数不确定的函数,示例如下
1 # 修饰入参数量不定的函数 2 def deco(func): 3 def _deco(*args, **kwargs): 4 print("before myfunc()") 5 res = func(a, b) 6 print(" after myfunc()") 7 return res 8 return _deco 9 10 @deco 11 def myfunc(a): 12 print(" myfunc() start") 13 print(a) 14 return True 15 16 @deco 17 def myfunc2(): 18 print(" myfunc() start") 19 print(a, b) 20 return True
3. 自身带有入参的装饰器,示例如下:
1 def deco(sign): 2 def wraper(func): 3 def _deco(*args, **kwargs): 4 print("%s before myfunc()"%sign) 5 res = func(a, b) 6 print(" after myfunc()") 7 return res 8 return _deco 9 return wraper 10 11 @deco("func1") 12 def myfunc(a): 13 print(" myfunc() start") 14 print(a) 15 return True 16 17 @deco("func2") 18 def myfunc2(): 19 print(" myfunc() start") 20 print(a, b) 21 return True
4. 带有类作为入参的装饰器,示例如下:
1 class locker: 2 def __init__(self): 3 print("locker.__init__() should be not called.") 4 5 @staticmethod 6 def acquire(): 7 print("locker.acquire()") 8 9 @staticmethod 10 def release(): 11 print(" locker.release() called") 12 13 # 作为入参的类必须实现acquire和release静态方法 14 def deco(cls): 15 def wraper(func): 16 def _deco(): 17 print("before %s called [%s]." % (func.__name__, cls)) 18 cls.acquire() 19 try: 20 return func() 21 finally: 22 cls.release() 23 return _deco 24 return wraper 25 26 @deco(locker) 27 def myfunc(): 28 print(" myfunc() called.")
四. configparser库
在这次完成的作业,实现用户系统存储在文件中的需求。如果信息不是很大,可以使用python中的configparser库来实现,更加方便。(在python2中该库叫ConfigParse,需要pip来安装)
该库实现了操作ini风格类型文件的各种方法。ini风格类型示例如下:
1 [111] 2 password = 222 3 admin_flag = 0 4 5 [222] 6 password = 333 7 admin_flag = 0 8 9 [444] 10 password = 555 11 admin_flag = 1
每个[]代表一个section,下面一个等号对代表这个section的一项属性和值。使用configparser的各种方法示例如下:
1 cf = configparser.ConfigParser() 2 # 读取文件 3 cf.read('a.conf') 4 5 # sections方法返回所有的section名字的列表 6 for sec in cf.sections(): 7 print(sec) 8 9 10 # 增加一个新的section 11 cf.addsection('555') 12 # 给新的section'555'增加属性 13 set('555', 'password', '3232') 14 15 16 # 原有的section的属性也可以更改,和增加的方法一致 17 set('444', 'password', '3232') 18 19 # 通过get和getint方法之类可以取到一个section的一个属性的值 20 cf.get('444', 'password') 21 cf.getint('444', 'password') 22 23 # 通过items可以获得一个section的所有属性 24 cf.items('444') 25 26 27 # 更改结束以后,用write修改文件 28 cf.write(open('a.conf', "w")
五. python内置的sorted用法
sorted是内置的对一个序列进行排序的方法,必须包含一个序列的入参,其他还有可选入参key,cmp(注意python3没这个了),reverse。
1. key参数的值为一个函数,此函数将在每个元素比较前被调用,它只有一个参数且返回一个值,让sorted用这里返回的值进行比较,示例如下:
1 student_tuples = [ 2 ('john', 'A', 15), 3 ('jane', 'B', 12), 4 ('dave', 'B', 10),] 5 # 这里取每个元素的最后一个元素比较 6 sorted(student_tuples, key=lambda student: student[2]) 7 8 # 这里就取每个字母的小写比较 9 sorted("This is a test string from Andrew".split(), key=str.lower)
2. cmp参数示例如下:
1 def numeric_compare(x, y): 2 return x - y 3 4 # cmp接受一个返回bool类型变量的函数, 5 # 用于定义一些比较比较 6 # 其入参代表序列中前后两个元素 7 sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
在网上找到一个很牛叉的,从2->3移植代码时候,转换cmp到key的方法如下:
1 def cmp_to_key(mycmp): 2 'Convert a cmp= function into a key= function' 3 class K(object): 4 def __init__(self, obj, *args): 5 self.obj = obj 6 def __lt__(self, other): 7 return mycmp(self.obj, other.obj) < 0 8 def __gt__(self, other): 9 return mycmp(self.obj, other.obj) > 0 10 def __eq__(self, other): 11 return mycmp(self.obj, other.obj) == 0 12 def __le__(self, other): 13 return mycmp(self.obj, other.obj) <= 0 14 def __ge__(self, other): 15 return mycmp(self.obj, other.obj) >= 0 16 def __ne__(self, other): 17 return mycmp(self.obj, other.obj) != 0 18 return K
调用的时候这样:
1 sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
3. reverse值为bool类型,即确定是否需要倒序排列。
浙公网安备 33010602011771号