正则
re 正则模块
时间模块
time
import time
time() #时间戳,通常给计算机用的
print(time.time()) #(时间戳)1970年至今经历的秒数(1970年是unix元年)
结构化时间
localtime
print(time.localtime().tm_year) #tm_year取当前年
print(time.localtime()) #取今年所有的时间
返回值:
time.struct_time(tm_year=2017, tm_mon=6, tm_mday=7, tm_hour=9, tm_min=56, tm_sec=39, tm_wday=2, tm_yday=158, tm_isdst=0)
print(time.gmtime()) #标准时间(格林威治时间,北京时间比标准时间晚上8小时),localtime比标准时间快了8个小时
格式化的字符串
print(time.strftime('%Y-%m-%d %H:%M:%S')) #年月日,时分秒,区分大小写
print(time.strftime('%Y-%m-%d %X')) #和上面的结果是一样的, %X代表的时分秒
asctime时间
print(time.asctime())
print(time.ctime(1111)) #时间戳转换成asctime(#把时间戳转换成 %a %b %d %H %M %S %Y串)
返回值:
Thu Jan 1 08:18:31 1970
各类型时间的转换
print(time.localtime(213233)) #把213233秒(时间戳)转换成结构化时间
print(time.localtime(time.time())) #把当前时间戳转换成结构化时间
print(time.gmtime(time.time())) #把当前时间戳转换成标准时间
print(time.gmtime(1111133)) #把1111133秒(时间戳)转换成标准时间
print(time.mktime(time.localtime())) #当前结构化时间转换成时间戳(s)
print(time.strftime('%Y %X',time.localtime())) #将年,时分秒从结构化转换成格式化
print(time.strptime('2017-06-04 11:59:33','%Y-%m-%d %X')) #字符串转换成结构化
print(time.ctime(1111)) #时间戳转换成asctime
print(time.asctime(time.localtime())) #将结构化时间转换成%a %b %d %H %M %S %Y串(asctime)
random模块
import random
# print(random.random()) #(0,1) 什么都不加默认取的是0和1之间的小数
# print(random.randint(1,3)) #[1,3] 大于等于1且小于等于3之间的整数
# print(random.randrange(1,3)) #[1,3] 大于等于1且小于3之间的整数
# print(random.choice([1,'23',[4,5]])) # 1或者23或者[4,5]
# print(random.sample([1,'23',[4,5]],2)) #列表元素任意两个组合,2代表随机两个组合
print(random.uniform(1,3)) #大于1小于3的小数,如1.137122064823889
item=[1,2,4,5,8]
random.shuffle(item) #打乱item的顺序,相当于洗牌
print(item)
随机选取一个代理ip
import random
proxy_ip=[
'127.0.0.1',
'192.168.1.7',
'114.114.114.114',
]
print(random.choice(proxy_ip))
生成随机数
import random
def v_code(n=5): #n=5位数
res=''
for i in range(n):
num=random.randint(0,9) #数字范围
s=chr(random.randint(65,90)) #assic码65,-90对应的是字母,chr 将数字转换成字母
add=random.choice([num,s]) #随机选择数字或者字母,拼成列表的形式
res+=str(add) #数字转换成字符串
return res
print(v_code(7)) #指定6个
返回值:
ALR7X88 (随机的)
os和sys模块
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: ('.')
os.pardir 获取当前目录的父目录字符串名:('..')
os.makedirs('dirname1/dirname2') 可生成多层递归目录
os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.stat('path/filename') 获取文件/目录信息
os.sep 输出操作系统特定的路径分隔符,win下为"\\",Linux下为"/"
os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n"
os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为:
os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
os.system("bash command") 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小
os.chidir('c \\') 切换到c目录下(仅限在windows使用,linux不管用)
print(os.path.abspath('a/b/c.txt')) 当前绝对路径加文件路径
返回值:C:\Users\Administrator\PycharmProjects\untitled\test\a\b\c.txt
print(os.path.abspath('/a/b/c.txt')) 当前盘符路径+文件路径
返回值:C:\a\b\c.txt
#取当前的绝对路径和当前的绝对目录路径
print(os.path.abspath(__file__))
print(os.path.dirname(__file__))
print(__file__) #获取当前路径
print(os.path.split('C:\\a\\b\\c.txt')) 切割路径,分割成目录和文件名两元组返回
print(os.path.dirname('C:\a\\b\\c.txt')) 查看最后一个目录
print(os.path.basename('C:\a\\b\\c.txt')) 取最后一个文件名
print(os.path.exists('C:\a\\b\\c.txt')) 查看路径是否存在
print(os.path.isabs('C:\a\\b\\c.tx')) 如果是绝对路径,返回trun
print(os.path.getsize(r'C:/Users/Administrator/PycharmProjects/untitled/test/test.py')) #getsize 获取文件大小
print(os.path.join('a','E:\\b','c.txt')) #将多个路径组合返回,第一个绝对路径之前的参数将被忽略
返回值:E:\b\c.txt
#normcase 在linux和mac平台上,该函数会原样返回path,在windows平台上将路径中所有字符转换为小写,并将所有斜杠转换为反斜杠
print(os.path.normcase('c:/windows\\system32\\'))
print(os.path.normcase('c:/windows\\sysTem32\\'))
返回值:c:\windows\system32\
c:\windows\system32\
#normpath 规范路径。如..和/
print(os.path.normpath('c:/windows\\sysTem32\\../tmp/')) #因为tmp实际是在windows下一级,所以system32实际上是没用的,所以会自动忽略system32。不会自动将大小转为小写
返回值:c:\windows\tmp
#print(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 获取第二个目录
#基于当前目录往下导入的模块都能导入
BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
另一种方式也可以
BASE_DIR=os.path.normpath(os.path.join(__file__,os.pardir,os.pardir))
print(BASE_DIR)
sys.argv #命令行参数list,第一个元素是程序本身的路径
sys.exit(n) #退出程序,正常退出时exit(0)
sys.version #获取python解释程序的版本信息
sys.maxint #最大的int值
sys.platform #返回操作系统平台名称
sys.path #返回模块的搜索路径,初始化时使用pythospath环境变量的值
实现进度条的功能

shutil模块
高级的文件,文件夹,压缩包处理模块
拷贝文件,可以覆盖
shutil.copyfileobj(open('test1.py','r'),open('test3.py','w'))
或者这样:
shutil.copyfile('test.py','test4.py')
shutil.copymode(src, dst)
仅拷贝权限,内容,组,用户均不变
shutil.copymode('f1.log', 'f2.log') #目标文件必须存在
shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
shutil.copystat('f1.log', 'f2.log') #目标文件必须存在
shutil.copy(src, dst)
拷贝文件和权限
shutil.copy('f1.log', 'f2.log')
shutil.copy2(src, dst)
拷贝文件和状态信息
shutil.copy2('f1.log', 'f2.log')
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #目标目录不能存在,注意对folder2目录父级目录要有可写权限,ignore的意思是排除
拷贝软连接
import shutil
shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
通常的拷贝都把软连接拷贝成硬链接,即对待软连接来说,创建新的文件
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
shutil.rmtree('folder1')
shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名
shutil.move('folder1', 'folder3')
shutil.make_archive(base_name, format,...)
创建压缩包并返回文件路径,例如:zip、tar
bash_name:压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至制定的路径
例如:data_bak =>保存至当前路径
如:/tmp/data_bak =>保存至/tmp/
format: 压缩包种类:“zip”, “tar”, “bztar”,“gztar”
root_dir: 要压缩的文件夹路径(默认当前目录)
owner: 用户,默认当前用户
group: 组,默认当前组
logger: 用于记录日志,通常是logging.Logger对象
例子:
#将 /data 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("data_bak", 'gztar', root_dir='/data')
#将 /data下的文件打包放置 /tmp/目录
import shutil
ret = shutil.make_archive("/tmp/data_bak", 'gztar', root_dir='/data')
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
zipfile压缩解压缩
import zipfile
# 压缩
z = zipfile.ZipFile('laxi.zip', 'w')
z.write('a.log')
z.write('data.data')
z.close()
# 解压
z = zipfile.ZipFile('laxi.zip', 'r')
z.extractall(path='.')
z.close()
tarfile压缩解压缩
mport tarfile
# 压缩
>>> t=tarfile.open('/tmp/egon.tar','w')
>>> t.add('/test1/a.py',arcname='a.bak')
>>> t.add('/test1/b.py',arcname='b.bak')
>>> t.close()
# 解压
>>> t=tarfile.open('/tmp/egon.tar','r')
>>> t.extractall('/egon')
>>> t.close()
以写的方式打开
import tarfile
t=tarfile.open('egon.tar','w')
t.add(r'C:/Users/Administrator/PycharmProjects/untitled/test/test1.py')
t.add(r'C:/Users/Administrator/PycharmProjects/untitled/test/test3.py')
t.close()
#解压缩
t=tarfile.open('egon.tar','r')
t.extractall('extract_dir1') #解压extract_dir1
#给压缩文件一个别名:
import tarfile
t=tarfile.open('egon.tar','w')
t.add(r'C:/Users/Administrator/PycharmProjects/untitled/test/test1.py'arcname='a.txt')
json模块
序列化:我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。
为什么要序列化:
1:持久保存状态
需知一个软件/程序的执行就在处理一系列状态的变化,在编程语言中,'状态'会以各种各样有结构的数据类型(也可简单的理解为变量)的形式被保存在内存中。
内存是无法永久保存数据的,当程序运行了一段时间,我们断电或者重启程序,内存中关于这个程序的之前一段时间的数据(有结构)都被清空了。
在断电或重启程序之前将程序当前内存中所有的数据都保存下来(保存到文件中),以便于下次程序执行能够从文件中载入之前的数据,然后继续执行,这就是序列化。
具体的来说,你玩使命召唤闯到了第13关,你保存游戏状态,关机走人,下次再玩,还能从上次的位置开始继续闯关。或如,虚拟机状态的挂起等。
2:跨平台数据交互
序列化之后,不仅可以把序列化后的内容写入磁盘,还可以通过网络传输到别的机器上,如果收发的双方约定好实用一种序列化的格式,那么便打破了平台/语言差异化带来的限制,实现了跨平台数据交互。
反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。
序列化json
如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。
JSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:


import json
dic={
'name':'alex',
'age':9000,
'height':'150cm'
}
json.dump(dic,open('b.json','w'))
序列化后:
{"name": "alex", "age": 9000, "height": "150cm"}
反序列化:
res=json.load(open('b.json','r'))
print(res,type(res))
返回值:
{'name': 'alex', 'age': 9000, 'height': '150cm'} <class 'dict'> #字典
序列化过程与反序列化过程


pickle模块
转换成的是bytes类型
import pickle
dic={'name':'alex','age':13}
print(pickle.dumps(dic))
shelve模块
shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型
import shelve
f=shelve.open(r'sheve.txt')
# f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# f['stu2_info']={'name':'gangdan','age':53}
# f['school_info']={'website':'http://www.pypy.org','city':'beijing'}
print(f['stu1_info']['hobby'])
f.close()
import shelve
f=shelve.open(r'sheve.t xt')
f['shudent1']={'name':'egon','age':18}
print(f['shudent1'])
f.close()
xml格式文件操作
xml格式通过<>节点来区别数据结构
<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>
xml协议在各个语言里的都 是支持的,在python中可以用以下模块操作xml:
print(root.iter('year')) #全文搜索
print(root.find('country')) #在root的子节点找,只找一个
print(root.findall('country')) #在root的子节点找,找所有
例子:
import xml.etree.ElementTree as ET
tree = ET.parse('b')
root = tree.getroot()
for i in root.iter('year'):
print(i.tag,i.text,i.attrib) #tag标签,text是内容,attrib是属性
·························
print(root.find('country')) #country是关键字,找到是子节点下的第一个
print(root.findall('country')) #找子节点下所有
-------------------------
#遍历xml文档
for child in root:
print('========>',child.tag,child.attrib,child.attrib['name'])
for i in child:
print(i.tag,i.attrib,i.text)
#只遍历year 节点
for node in root.iter('year'):
print(node.tag,node.text)
--------------------------------
删除,修改
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
#修改
for node in root.iter('year'):
new_year=int(node.text)+1
node.text=str(new_year)
node.set('updated','yes')
node.set('version','1.0')
tree.write('test.xml')
#删除node
for country in root.findall('country'):
rank = int(country.find('rank').text)
if rank > 50:
root.remove(country)
tree.write('output.xml')
---------------------------
#在country内添加(append)节点year2
import xml.etree.ElementTree as ET
tree = ET.parse("a.xml")
root=tree.getroot()
for country in root.findall('country'):
for year in country.findall('year'):
if int(year.text) > 2000:
year2=ET.Element('year2')
year2.text='新年'
year2.attrib={'update':'yes'}
country.append(year2) #往country节点下添加子节点
tree.write('a.xml.swap')
---------------------------------
import xml.etree.ElementTree as ET
new_xml = ET.Element("namelist")
name = ET.SubElement(new_xml,"name",attrib={"enrolled":"yes"})
age = ET.SubElement(name,"age",attrib={"checked":"no"})
sex = ET.SubElement(name,"sex")
sex.text = '33'
name2 = ET.SubElement(new_xml,"name",attrib={"enrolled":"no"})
age = ET.SubElement(name2,"age")
age.text = '19'
et = ET.ElementTree(new_xml) #生成文档对象
et.write("test.xml", encoding="utf-8",xml_declaration=True)
ET.dump(new_xml) #打印生成的格式
hashlib模块
hash:一种算法 ,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
三个特点:
1.内容相同则hash运算结果相同,内容稍微改变则hash值则变
2.不可逆推
3.相同算法:无论校验多长的数据,得到的哈希值长度固定。
缺点:
通过撞库可以反解,需要对加密算法中添加自定义key再来做加密。
md5校验一个文件,md5校验的是bytes格式,所有用rb
import hashlib
m=hashlib.md5()
with open(r'C:/Users/Administrator/PycharmProjects/untitled/test/test.py','rb') as f:
for line in f:
m.update(line)
md5_num=m.hexdigest()
print(md5_num)
update:可以在一同时间里内存只有一行内容,第二次update会覆盖第一个update的内容,但是其实是基于上一行的值计算的,所以内存用的少,防止内存溢出
下面是对比的例子
m.update('hello',encode('utf-8'))
m.update('world',encode('uft-8'))
----------------------
m.update('helloworld',encode('utf-8'))
添加key做加密
import hashlib
s=hashlib.sda256()
s.update('helloworld'.encode='utf-8')
print(s.hexdigest())
通过加密一行字符串+密码,从而增加破解的难度
import hashlib
m=hashlib.md5('helloworld'.encode('utf-8')) #加一行加密的字符串
m.update('alex'.encode('utf-8')) #这个是密码,通过加上面的加密的字符串,两相叠加后密码不容易破解
print(m.hexdigest())
subprocess模块
import subprocess
res=(subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE))
print(res)
print(res.stdout.read().decode('gbk'))
logging模块
日志级别:
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
如果不指定filename,则默认打印到终端
#指定日志级别:
指定方式:
level=10
level=logging.ERRO
指定日志级别为ERROR,则只有ERROR及其以上级别的日志会被打印
'''
logging.basicConfig(filename='access.log',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p',
level=10)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log') #如果level=40,则只有logging.critical和loggin.error的日志会被打印
logging.basicConfig()函数中通过具体参数来更改logging模块默认行为,可用参数有:
filename:用指定的文件名创建FiledHandler(后边会具体讲解handler的概念),这样日志会被存储在指定的文件中。
filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format:指定handler使用的日志显示格式。
datefmt:指定日期时间格式。
level:设置rootlogger(后边会讲解具体概念)的日志级别
stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略
日志格式:


configparser模块
配置文件:
# 注释1
; 注释2
[section1]
k1 = v1
k2:v2
user=egon
age=18
is_admin=true
salary=31
[section2]
k1 = v1
读取:
import configparser
config=configparser.ConfigParser()
config.read('a.cfg')
#查看所有的标题
res=config.sections() #['section1', 'section2']
print(res)
#查看标题section1下所有key=value的key
options=config.options('section1')
print(options) #['k1', 'k2', 'user', 'age', 'is_admin', 'salary']
#查看标题section1下所有key=value的(key,value)格式
item_list=config.items('section1')
print(item_list) #[('k1', 'v1'), ('k2', 'v2'), ('user', 'egon'), ('age', '18'), ('is_admin', 'true'), ('salary', '31')]
#查看标题section1下user的值=>字符串格式
val=config.get('section1','user')
print(val) #egon
#查看标题section1下age的值=>整数格式
val1=config.getint('section1','age')
print(val1) #18
#查看标题section1下is_admin的值=>布尔值格式
val2=config.getboolean('section1','is_admin')
print(val2) #True
#查看标题section1下salary的值=>浮点型格式
val3=config.getfloat('section1','salary')
print(val3) #31.0
改写:
import configparser
config=configparser.ConfigParser()
config.read('a.cfg')
#删除整个标题section2
config.remove_section('section2')
#删除标题section1下的某个k1和k2
config.remove_option('section1','k1')
config.remove_option('section1','k2')
#判断是否存在某个标题
print(config.has_section('section1'))
#判断标题section1下是否有user
print(config.has_option('section1',''))
#添加一个标题
config.add_section('egon')
#在标题egon下添加name=egon,age=18的配置
config.set('egon','name','egon')
config.set('egon','age',18) #报错,必须是字符串
#最后将修改的内容写入文件,完成最终的修改
config.write(open('a.cfg','w'))
获取所有节点
import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
res=config.sections()
print(res)
'''
打印结果:
['bitbucket.org', 'topsecret.server.com']
'''
获取指定节点下所有的键值对
import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
res=config.items('bitbucket.org')
print(res)
'''
打印结果:(包含DEFAULT以及bitbucket.org这俩标题下所有的items)
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')] ```
获取指定节点下所有的建
import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
res=config.options('bitbucket.org')
print(res)
'''
打印结果:(包含DEFAULT以及bitbucket.org这俩标题下所有的键)
['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']'''
获取指定节点下指定key的值
import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
res1=config.get('bitbucket.org','user')
res2=config.getint('topsecret.server.com','port')
res3=config.getfloat('topsecret.server.com','port')
res4=config.getboolean('topsecret.server.com','ForwardX11')
print(res1)
print(res2)
print(res3)
print(res4)
'''
打印结果:
hg
50022
50022.0
False
'''
检查、删除、添加节点
import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
#检查
has_sec=config.has_section('bitbucket.org')
print(has_sec) #打印True
#添加节点
config.add_section('egon') #已经存在则报错
config['egon']['username']='gangdan'
config['egon']['age']='18'
config.write(open('test.ini','w'))
#删除节点
config.remove_section('egon')
config.write(open('test.ini','w'))
检查、删除、设置指定组内的键值对
import configparser
config=configparser.ConfigParser()
config.read('test.ini',encoding='utf-8')
#检查
has_sec=config.has_option('bitbucket.org','user') #bitbucket.org下有一个键user
print(has_sec) #打印True
#删除
config.remove_option('DEFAULT','forwardx11')
config.write(open('test.ini','w'))
#设置
config.set('bitbucket.org','user','gangdang')
config.write(open('test.ini','w'))
类与对象
先有类后有对象
类是一系列对象共有的特征(变量)与技能(函数)的结合体
class foo:
'''文档注释'''
pass
class chinese:
print('====>')
country='china'
def talk(self):
print('talking')
p=chinese()
print(p)
属性引用:
print(chinese.country)
print(chinese.talk)
实例化:
p1=chinese()
print(p1)
#对象的使用:属性引用
print(p1.country)
类与对象的名称空间以及绑定方法
类的空间:
print(chinese.__dict__)
对象的空间:
p1=chinese('egon',18,'male')
print(p1.__dict__)
print(p1.age)
浙公网安备 33010602011771号