1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
一、模块介绍
os模块常用方法
os.getcwd()    #获取当前工作目录
os.listdir("F:\\")    #获取指定目录下的所有文件和目录
os.remove('b.json')    #删除指定文件
os.stat('a.json')    #获取文件属性
os.chmod()        #修改文件属性
os.mkdir('hyh')    #创建目录
os.rmdir('hyh')    #删除目录
os.system('dir')    #运行shell命令
os._exit(2)        #终止当前进程
os.path.split('/root/a.json')    #返回路径的目录名和文件名组成的元组,('/root', 'a.json')
os.path.isfile('a.json')    #校验是否是文件,是则返回True,否则返回False
os.path.isdir('hyh')        #校验是否是目录,是则返回True,否则返回False
os.path.exists('hyh')    #校验路径是否存在,是则返回True,否则返回False
os.curdir    #返回当前目录
os.chdir('hyh')    #改变当前目录到'hyh'
print(os.path.abspath('.'))    #获取指定目录的绝对路径
os.path.splitext('a.json')    #分离文件名和扩展名,返回文件名和扩展名的元组,('a', '.json')
os.path.join('\\root','a.json')    #连接目录和文件,\root\a.json
os.path.basename('/root/a.json')    #返回文件名
os.path.dirname('/root/a.json')    #返回目录名
 
sys模块常用方法
sys.argv    #返回从外部传递的参数
sys.exit(2)    #退出程序
sys.getdefaultencoding()    #获取系统编码
sys.path    #获取系统环境变量集合,可以将需要的模块或者变量添加进去
sys.platform    #获取系统平台
 
将当前目录加入环境变量
dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(dir)
 
hashlib模块常用方法
md5: 加密字符串
例子
import hashlib
string = 'hyonghui'
= hashlib.md5()
m.update(string.encode('utf-8'))
res = m.hexdigest()    #把字符串摘要转换成16进制字符串
print(res)
 
m1 = hashlib.md5('hyong'.encode('utf-8'))
m1.update('hui'.encode('utf-8'))
res1 = m1.hexdigest()
print(res1)
 
res和res1打印结果相同
 
sha256    #
sha = hashlib.sha256()
sha.update(string.encode('utf-8'))
res = sha.hexdigest()
print(res)
 
sha1 = hashlib.sha256('hyong'.encode('utf-8'))
sha1.update('hui'.encode('utf-8'))
res1 = sha1.hexdigest()
print(res1)
 
 
pickle模块使用方法
pickle序列化和反序列化数据
例子:
import pickle
dic = {'name''alex''age'13}
print(pickle.dumps(dic))    #dumps函数序列化dic
with open('a.pkl''wb') as f:
    f.write(pickle.dumps(dic))
     
with open('a.pkl''rb') as f:
    res = pickle.loads(f.read())    #loads反序列化字符串成字典
    print(res,type(res))
     
dic = {'name''alex''age'13}
pickle.dump(dic, open('b.pkl''wb'))
res = pickle.load(open('b.pkl''rb'))
print(res,type(res))
 
import json
import pickle
def func():
    print('from func')
 
#json.dumps(func)# 报错,json不支持python的函数类型
f=pickle.dumps(func)
print(f)
 
pickle.dump(func,open('c.pkl','wb'))
res=pickle.load(open('c.pkl','rb'))
print(res)
res()
 
json模块使用方法
json序列化对象以字符串方式保存到文件,并且可以反序列化,可以跨语言
例子:
序列化
import json
dic = {
    'name''alex',
    'age'9000,
    'height''150cm'
}
 
res = json.dumps(dic)
print(res,type(res))
with open('b.json''w') as f:
    f.write(res)
 
反序列化
import json
 
with open('b.json''r') as f:
    dic = json.loads(f.read())
    print(dic, type(dic))
 
shelve序列化
import shelve
= shelve.open(r'sheve.txt')
f['student'= {'name''alex''age':18'height':'180cm'}
print(f['student']['name'])
f.close()
     
random模块使用方法
random.random()    #生成0~1的随机数,随机数大于0小于1 
random.uniform(10,20)    #生成指定范围的随机数,随机数大于m小于n
random.randint(10,20)    #生成指定范围的随机整数,  10<=n<=20
random.randrange(10,20,2)    #生成指定范围的随机整数, 10<=n<20 步长是2
import random
proxy_ip = [
    '1.1.1.1',
    '2.2.2.2',
    '3.3.3.3',
    '4.4.4.4'
]
= random.choice(proxy_ip)    #从序列中随机选取一个
print(v)
 
list = [12345678910]
print(random.sample(list5))    #随机选取指定长度的元素组成新的列表
 
生成5位随机数代码
def v_code(n):
    res = ''
    for in range(n):
        num = random.randint(0,9)
        = chr(random.randint(65,90))
        = str(random.choice([num,s]))
        res += v
    print(res)
v_code(5)
 
 
time模块常用方法
time.time()    #打印时间戳
print(time.localtime())    #结构化的时间
print(time.localtime().tm_year)
time.strftime('%Y-%m-%d %H:%M:S', time.localtime())    #按照固定格式打印时间
time.ctime()    #Mon Jun  5 14:55:03 2017
 
 
shutil模块常用方法
shutil实现文件复制功能
shutil.copyfile('a.json''a.txt')    #a.json为源文件,a.txt为目标文件
shutil.copyfileobj(open('a.json''r'), open('a.py''w'))
shutil.make_archive('data_bak''gztar', root_dir=r'E:\python\oldboyday6')    #归档操作
 
压缩解压缩
import shutil
shutil.copyfile('a.json''a.txt')
shutil.copyfileobj(open('a.json''r'), open('a.py''w'))
 
shutil.make_archive('data_bak''gztar', root_dir=r'E:\python\oldboyday6')
 
import tarfile
t= tarfile.open('data_bak.tar.gz''r')
t.extractall('extract_dir')
t.close()
 
subprocess模块常用方法
例子:
import subprocess
res = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE)    #标准输出给管道
print(res)
print(res.stdout.read().decode('gbk'))
 
import subprocess
res = subprocess.Popen('axlajsajen',shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
print(res)
print(res.stdout.read())
print(res.stderr.read().decode('gbk'))
 
import subprocess
res1 = subprocess.Popen(r'dir E:\python\oldboyday6',shell=True, stdout=subprocess.PIPE)
res = subprocess.Popen(r'findstr txt*', shell=True, stdin=res1.stdout, 
stdout=subprocess.PIPE, stderr=subprocess.PIPE)    #res1输出传递给stdin
print(res.stdout.read().decode('gbk'))
 
xml模块常用方法介绍
xml模块解析xml文件
例子:
import xml.etree.ElementTree as ET
 
tree = ET.parse('country.xml')
root = tree.getroot()    #获取根标签对象
 
for in root.iter('year'):
    print(i.tag,i.text,i.attrib)    #打印标签,标签内容,标签属性 year 2009 {'update': 'yes'}
 
print(root.find('country'))    #找到第一个country标签所在位置
print(root.findall('country'))    #找到所有country标签所在位置
for country in root:
    print('====>', country.attrib['name'])
    for item in country:
        print(item.tag, item.text, item.attrib)
         
for in root.iter('year'):
    i.text = str(int(i.text) + 1)
    i.set('update''yes')    #给标签添加属性
 
tree.write('b.xml')    #将country.xml的内容写到b.xml
 
生成xml文档
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)
 
configparse模块方法介绍
配置文件a.ini
[section1]
k1 = v1
k2:v2
db=pymysql+mysql://egon:123@192.168.2.3/db1
max_conn=30
enable=1
[section2]
k1 = v1
 
import configparser
config = configparser.ConfigParser()
config.read('a.ini')
 
print(config.sections())    #得到所有的section,并以列表方式返回['section1', 'section2']
print(config.get('section1''db'))    #过滤含有db关键字的匹配项,pymysql+mysql://egon:123@192.168.2.3/db1
print(config.getint('section1','max_conn'))    #和get函数相似,返回int类型
print(config.getboolean('section1''enable'))    #返回布尔值
print(config.has_option('section1''enable'))    #判断是否有enable配置项
print(config.remove_option('section1''enable'))    #删除某个配置
 
添加配置
import configparser
config = configparser.ConfigParser()
config.add_section('egon')
config.set('egon','name','egon')
config.set('egon''age''18')
 
config.write(open('b.ini','w'))
 
logging模块方法介绍
例子:
import logging
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=40
                    )
 
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')