201106-Python自动化常用模块介绍

Python自动化常用模块介绍

python自有模块正则

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import re

# re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None
print(re.match("blog", "blog.laosan.xin").group()) # 在起始位置匹配
print(re.match("laosan", "blog.laosan.xin")) # 不在起始位置匹配,返回None

# re.search扫描整个字符串并返回第一个成功的匹配
print(re.search("laosan", "blog.laosan.xin").group())

# re.findall从左到右扫描字符串,按顺序返回匹配,如果无匹配结果则返回空列表
print(re.findall("\d", "one1two2three3four4"))
print(re.findall("\d", "onetwothreefour"))

# sub用于替换字符串中的匹配项
print(re.sub("g..t", "good", "goot geet up"))

# split返回切割后的列表
print(re.split("\+", "123+456*789+abcd"))

re.compile将正则字符串编译成正则表达式对象:

1
2
3
4
5
6
7

# re.compile将正则字符串编译成正则表达式对象:
datetime = '2020-11-06 12:30:30'
peet = re.compile("\d{2}\d{2}:\d{2}")
print("将时分秒提取为表达式对象", peet)
result = re.sub(peet, "", datetime)
print("将时分秒提取值为", result)

正则表达式

python第三方模块操作MySQL

连接数据库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
config = {
"host": "127.0.0.1",
"user": "root",
"passwd": "root@123",
"port": 3306,
"db": "user",
"charset": "utf8",
"buffered": "True"
}

# 插入输入
try:
db = mysql.connector.connect(**config)
# print(db.autocommit)
except mysql.connector.Error as e:
print("连接数据库失败!", str(e))

插入数据

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
# 插入输入
try:
db = mysql.connector.connect(**config)
# print(db.autocommit)
except mysql.connector.Error as e:
print("连接数据库失败!", str(e))

# buffered=True会把结果集保存到本地并一次性返回,这样可以提高性能
cursor = db.cursor(buffered=True)
try:

autocommit = "SELECT @@session.autocommit"
# sql_insert1="insert into user (name, age) values ('laosan', 30)"
print(cursor.execute(autocommit))

# 第二种:元组连接插入方式
sql_insert2 = "insert into user (name, age) values (%s, %s)"

# 此处的%s为占位符,而不是格式化字符串,所以age用%s
data = ('laosan', random.randint(0, 100000000))
cursor.execute(sql_insert2, data)

data = [("xiao", 20), ("xian", 25), ("rourou", 27), ("juju", 28)]
cursor.executemany(sql_insert2, data)

# 如果表引擎为Innodb,执行完成后需执行commit进行事务提交
db.commit()
except mysql.connector.Error as e:
print('插入失败!', str(e))
finally:
cursor.close()

删除数据

1
2
3
4
5
6
7
8
9
10
11
# 删除数据
cursor = db.cursor(buffered=True)
try:
sql_del = "delete from user where name=%s and age=%s"
data_del = [("laosan", "30")]
cursor.executemany(sql_del, data_del)
db.commit()
except mysql.connector.Error as e:
print("删除数据失败!", str(e))
finally:
cursor.close()

修改数据

1
2
3
4
5
6
7
8
9
cursor = db.cursor(buffered=True)
try:
sql_update = "update user set age = 28 where name='laosan'"
cursor.execute(sql_update)
db.commit()
except mysql.connector.Error as e:
print("修改数据失败!", str(e))
finally:
cursor.close()

查询数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
cursor = db.cursor(buffered=True)
try:
sql_select = "select * from user where age > %s"
cursor.execute(sql_select,(26,))

# 查询所有数据
datas1 = cursor.fetchall()

# 如果在后加上[1]代表是取第一条数据
cursor.execute(sql_select,(20,))
datas2 = cursor.fetchone()[1]
# 返回5条
datas3 = cursor.fetchmany(5)
print(datas1)
print(datas2)
print(datas3)
except mysql.connector.Error as e:
print("查询数据失败!",str(e))
finally:
cursor.close()

python第三方模块操作Excel

注意高能:openpyxl只能操作xlsx文件而不能操作xls文件!所以在创建的时候一定要新建.xlsx格式的Excel!!!

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
import openpyxl

# 打开文件
path_file = "/Users/laosan/Desktop/e/4-1.xlsx"
wb = openpyxl.load_workbook(path_file)

print("获取所有工作表名", wb.sheetnames)

# 获取指定的工作表sheet
sheet = wb["Sheet1"]
print("获取指定的工作表名:", sheet.title)

# 操作单元格:数据的读取与写入
# 获取单元格数据
print(sheet['A1'].value)

# 获取第二行第一列的值
print(sheet.cell(row=2, column=1).value)

# 数据的写入

sheet.cell(row=4, column=1).value = "修改后的内容"

sheet['C3'] = 'cs'

print("最大列数", sheet.max_column)
print("最大行数", sheet.max_row)

wb.save("/Users/laosan/Desktop/e/open.xlsx")
wb.save(path_file) #覆盖保存

参考资料

python自动化–模块操作之re、MySQL、Excel

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×