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

二. python一些内置函数整理

详细的官网文档链接 https://docs.python.org/3/library/functions.html
三. 装饰器
装饰器实际是一种接受函数作为参数的函数的语法糖。
1. 最普通的装饰器示例如下:
# 修饰不需要入参的函数
def deco(func):
def _deco():
print("before myfunc()")
res = func()
print(" after myfunc()")
return res
return _deco @deco
def myfunc():
print(" myfunc() start")
return True # 修饰有入参的函数
def deco2(func):
def _deco(a, b):
print("before myfunc()")
res = func(a, b)
print(" after myfunc()")
return res
return _deco @deco2
def myfunc2():
print(" myfunc() start")
print(a, b)
return True
2. 修饰参数不确定的函数,示例如下
# 修饰入参数量不定的函数
def deco(func):
def _deco(*args, **kwargs):
print("before myfunc()")
res = func(a, b)
print(" after myfunc()")
return res
return _deco @deco
def myfunc(a):
print(" myfunc() start")
print(a)
return True @deco
def myfunc2():
print(" myfunc() start")
print(a, b)
return True
3. 自身带有入参的装饰器,示例如下:
def deco(sign):
def wraper(func):
def _deco(*args, **kwargs):
print("%s before myfunc()"%sign)
res = func(a, b)
print(" after myfunc()")
return res
return _deco
return wraper @deco("func1")
def myfunc(a):
print(" myfunc() start")
print(a)
return True @deco("func2")
def myfunc2():
print(" myfunc() start")
print(a, b)
return True
4. 带有类作为入参的装饰器,示例如下:
class locker:
def __init__(self):
print("locker.__init__() should be not called.") @staticmethod
def acquire():
print("locker.acquire()") @staticmethod
def release():
print(" locker.release() called") # 作为入参的类必须实现acquire和release静态方法
def deco(cls):
def wraper(func):
def _deco():
print("before %s called [%s]." % (func.__name__, cls))
cls.acquire()
try:
return func()
finally:
cls.release()
return _deco
return wraper @deco(locker)
def myfunc():
print(" myfunc() called.")
四. configparser库
在这次完成的作业,实现用户系统存储在文件中的需求。如果信息不是很大,可以使用python中的configparser库来实现,更加方便。(在python2中该库叫ConfigParse,需要pip来安装)
该库实现了操作ini风格类型文件的各种方法。ini风格类型示例如下:
[]
password =
admin_flag = []
password =
admin_flag = []
password =
admin_flag =
每个[]代表一个section,下面一个等号对代表这个section的一项属性和值。使用configparser的各种方法示例如下:
cf = configparser.ConfigParser()
# 读取文件
cf.read('a.conf') # sections方法返回所有的section名字的列表
for sec in cf.sections():
print(sec) # 增加一个新的section
cf.addsection('')
# 给新的section'555'增加属性
set('', 'password', '') # 原有的section的属性也可以更改,和增加的方法一致
set('', 'password', '') # 通过get和getint方法之类可以取到一个section的一个属性的值
cf.get('', 'password')
cf.getint('', 'password') # 通过items可以获得一个section的所有属性
cf.items('') # 更改结束以后,用write修改文件
cf.write(open('a.conf', "w")
五. python内置的sorted用法
sorted是内置的对一个序列进行排序的方法,必须包含一个序列的入参,其他还有可选入参key,cmp(注意python3没这个了),reverse。
1. key参数的值为一个函数,此函数将在每个元素比较前被调用,它只有一个参数且返回一个值,让sorted用这里返回的值进行比较,示例如下:
student_tuples = [
('john', 'A', 15),
('jane', 'B', 12),
('dave', 'B', 10),]
# 这里取每个元素的最后一个元素比较
sorted(student_tuples, key=lambda student: student[2]) # 这里就取每个字母的小写比较
sorted("This is a test string from Andrew".split(), key=str.lower)
2. cmp参数示例如下:
def numeric_compare(x, y):
return x - y # cmp接受一个返回bool类型变量的函数,
# 用于定义一些比较比较
# 其入参代表序列中前后两个元素
sorted([5, 2, 4, 1, 3], cmp=numeric_compare)
在网上找到一个很牛叉的,从2->3移植代码时候,转换cmp到key的方法如下:
def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class K(object):
def __init__(self, obj, *args):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
def __le__(self, other):
return mycmp(self.obj, other.obj) <= 0
def __ge__(self, other):
return mycmp(self.obj, other.obj) >= 0
def __ne__(self, other):
return mycmp(self.obj, other.obj) != 0
return K
调用的时候这样:
sorted([5, 2, 4, 1, 3], key=cmp_to_key(reverse_numeric))
3. reverse值为bool类型,即确定是否需要倒序排列。
python基础整理笔记(四)的更多相关文章
- python基础整理笔记(一)
一. 编码 1. 在python2里,加载py文件会对字符进行编码,需要在文件头上的注释里注明编码类型(不加则默认是ascII). # -*- coding: utf-8 -*- print 'hel ...
- python基础整理笔记(九)
一. socket过程中注意的点 1. 黏包问题 所谓的黏包就是指,在TCP传输中,因为发送出来的信息,在接受者都是从系统的缓冲区里拿到的,如果多条消息积压在一起没有被读取,则后面读取时可能无法分辨消 ...
- python基础整理笔记(八)
一. python反射的方式来调用方法属性 反射主要指的就是hasattr.getattr.setattr.delattr这四个函数,作用分别是检查是否含有某成员.获取成员.设置成员.删除成员. 此外 ...
- python基础整理笔记(五)
一. python中正则表达式的一些查漏补缺 1. 给括号里分组的表达式加上别名:以便之后通过groupdict方法来方便地获取. 2. 将之前取名为"name"的分组所获得的 ...
- python基础整理笔记(二)
一. 列表 1. 创建实例: a = [1,2,3] b = list() 2. 主要支持的操作及其时间复杂度如下: 3. 其他 python中的列表,在内存中实际存储的形式其实是分散的存储,比较类似 ...
- python基础整理笔记(七)
一. python的类属性与实例属性的注意点 class TestAtt(): aaa = 10 def main(): # case 1 obj1 = TestAtt() obj2 = TestAt ...
- python基础整理笔记(三)
一. python的几种入参形式:1.普通参数: 普通参数就是最一般的参数传递形式.函数定义处会定义需要的形参,然后函数调用处,需要与形参一一对应地传入实参. 示例: def f(a, b): pri ...
- python基础整理笔记(六)
一. 关于hashlib模块的一些注意点 hashlib模块用于加密相关的操作,代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512, MD ...
- 0003.5-20180422-自动化第四章-python基础学习笔记--脚本
0003.5-20180422-自动化第四章-python基础学习笔记--脚本 1-shopping """ v = [ {"name": " ...
随机推荐
- Git服务器、http协议及XCode
本来费了老鼻子牛劲搭好了SVN,可以通过web进行访问,也弄好了eclipse和XCode,结果几个开发的同事说要上git,悲了个催,又开始折腾git. 因为公司只有一个公网的http出口,因此开始了 ...
- spring数据源配置
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-// ...
- java日期比较,日期计算
版权声明:本文为楼主原创文章,未经楼主允许不得转载,如要转载请注明来源. 都是常用的日期之间的比较方法,供以后参考. 热身:获取当前时间 SimpleDateFormat df = new Simpl ...
- Sturts2 工作原理
上图来源于Struts2官方站点,是Struts 2 的整体结构. 一个请求在Struts2框架中的处理大概分为以下几个步骤(可查看源码:https://github.com/apache/strut ...
- ASP.NET 操作Cookie详解 增加,修改,删除
ASP.NET 操作Cookie详解 增加,修改,删除 Cookie,有时也用其复数形式Cookies,指某些网站为了辨别用户身份而储存在用户本地终端上的数据(通常经过加密).定义于RFC2109.它 ...
- nuint笔记
注意:单元测试中,Case 与 Case 之间不能有任何关系 测试方法不能有返回值,不能有参数,测试方法必须声明为 public [TestFixture] //声明测试类 [SetUp] //建立, ...
- 在where条件中使用CASE WHEN 语句
CREATE TABLE TB_Test_Report ( id int identity, stateid int, userid int, username ) ) go ,,'a') ,,'b' ...
- 第一零五天上课 PHP TP框架下分页
控制器代码(TestController.class.php) <?php namespace Home\Controller; use Home\Controller\EmptyControl ...
- 关于Android开发手机连接不上电脑问题解决方案
1.当然首先你得将手机里的usb debug选项选上,否则lsusb是不会有你的设备的2. lsusb 查看usb设备id3. sudo vim /etc/udev/rules.d/51-androi ...
- SQLServer 命令批量删除数据库中指定表(游标循环删除)
DECLARE @tablename VARCHAR(30),@sql VARCHAR(500)DECLARE cur_delete_table CURSOR READ_ONLY FORWARD_ON ...