原文中还有 web开发常用的组件代码,由于我不做Python web 开发。所以去掉了,原文一共是有120多个代码的。

如果需要请支持原文作者!

原文链接:https://liangdongchang.blog.csdn.net/article/details/884251

1. 生成6位数字随机验证码

1
2
3
4
5
6
7
8
9
10
11
12
import random
import string


def num_code(length=6):
"""
生成长度为length的数字随机验证码
:param length: 验证码长度
:return: 验证码
"""

return ''.join(random.choice(string.digits) for i in range(0, length))

2、生成二维码

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
import qrcode
import io

def maker_qrcode(url):
"""
生成二维码
:param url: 需要生成二维码的url
:return: 返回图片字节流
"""
image = qrcode.make(url) # 创建二维码片

buffer = io.BytesIO()
# 将图片内容丢入容器
image.save(buffer, 'png')
# 返回容器内的字节
return buffer.getvalue()

或者
from .settings import BASE_DIR

def create_qrcode(name, url):
"""
生成机器扫码支付二维码
:param name: 图片名称
:param url: 支付路由
:return:
"""
img = qrcode.make(url, border=0) # 创建二维码片
save_path = BASE_DIR + '/' + name + '.png'
print(save_path)
img.save(save_path)
return img


3.微信群发

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
# coding=utf8
import itchat, time

itchat.auto_login(True)

SINCERE_WISH = u'祝%s新年快乐!'

friendList = itchat.get_friends(update=True)[35:]
count = 0

for index,friend in enumerate(friendList):
print(index,friend['DisplayName'],friend['NickName'])
itchat.send(SINCERE_WISH % (friend['DisplayName']
or friend['NickName']), friend['UserName'])
time.sleep(2)
print('备注名称',friend['DisplayName'],'昵称',friend['NickName'],'用户名',friend['UserName'])

print("----end----")

"""
# 发送文本
itchat.send('Hello, WeChat!')
# 发送图片
itchat.send_image('my_picture.png')
# 发送视频
itchat.send_video('my_video.mov')
# 发送文件
itchat.send_file('my_file.zip')

"""

4、微信自动回复

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
# -*- coding=utf-8 -*-
import requests
import itchat
import random
#图灵机器人
#http://www.tuling123.com/member/robot/1380138/center/frame.jhtml?page=0&child=0获取apikey
KEY = '你的KEY'

def get_response(msg):
apiUrl = 'http://www.tuling123.com/openapi/api'
data = {
'key' : KEY,
'info' : msg,
'userid' : 'wechat-robot',
}
try:
r = requests.post(apiUrl, data=data).json()
return r.get('text')
except:
return

@itchat.msg_register(itchat.content.TEXT)
def tuling_reply(msg):
defaultReply = 'I received: ' + msg['Text']
robots=['','','']
reply = get_response(msg['Text'])+random.choice(robots)
return reply or defaultReply

itchat.auto_login(enableCmdQR=False)
itchat.run()

5、数据库中给表创建数据

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

def createData(dataDict,tableName):
"""
给数据表创建数据
:param dataDict: 字典
:param tableName: 表名
:return:
"""
#连接数据库
conn = pymysql.connect(
host='192.168.0.188', #数据库所在地址URL
user='root', #用户名
password='123456', #密码
database='名称', #数据库名称
port=3306, #端口号
charset='utf8'
)
#拿到查询游标
cursor = conn.cursor()
clos,value = zip(*dataDict.items())
sql = "INSERT INTO `%s`(%s) VALUES (%s)" % (tableName,
','.join(clos),
','.join(['%s'] * len(value))
)
print(sql)
cursor.execute(sql, value)
conn.commit()
cursor.close()
conn.close()
print('Done')

6.捕捉异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
try:
pass
except 异常类型 as e:
pass
finally:
pass


异常类型
Exception 全部异常
AttributeError 试图访问一个对象没有的属性,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的

7、获取当前时间

1
2
3
4
5
6
7
8
9
import datetime

current_time = str(datetime.datetime.now())[:19]
print(current_time)

输出格式如:2018-10-20 10:01:43
local_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
print(local_time)

8、linux后台运行python程序

1
nohup /home/project_venv/user/bin/python3 -u /home/user/user_server.py >> /home/user/user.log 2>&1 &   

9、写/读CSV文件,查看是否存在,若存在就从csv中删除

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
import csv
import random
import string


def create_invite_code(random_code_pool=None, length=6, num=10, is_append=False):
"""
创建随机邀请码,并写入txt文件
:param: random_code_pool 随机邀请码
:param: length 邀请码长度
:param: num 邀请码个数
:param: is_append True追加,False 覆盖
:return:
"""
if not random_code_pool:
code_pool = string.ascii_uppercase + string.digits
random_code_pool = []
for i in range(num):
s = ''
for _ in range(length):
s += random.choice(code_pool)
if s and s not in random_code_pool:
random_code_pool.append(s)

# 写入方法。是追加还是覆盖
write_method = 'a+' if is_append else 'w'
# 写入文件
with open('./invite_code.csv', write_method, newline='') as f:
writer = csv.writer(f)
for rowData in random_code_pool:
# 按行写入
writer.writerow((rowData,))


def check_invite_code(code):
"""
查看邀请码是否存在txt文件中,
若存在就返回True,并在txt文件中删除
若不存在就返回False
:param code:
:return:
"""
code_pool = []
with open('./invite_code.csv', 'r', encoding='utf-8',errors='ignore') as f:
allFileInfo = csv.reader(f)
for row in allFileInfo:
code_pool.append(row[0])

if code in code_pool:
# 删除查询的code
code_pool.pop(code_pool.index(code))

# 重新写入文件
create_invite_code(code_pool,is_append=False)
return True
return False


if __name__ == '__main__':
# create_invite_code(length=9,num=100)
print(check_invite_code('WJ4PSTJG2'))


10、删除指定格式的文件

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


def remove_specified_format_file(file_dir, format_name):
"""
删除指定格式的文件
:param file_dir: 文件根目录
:param format_name: 格式
:return:
"""
for root, dirs, files in os.walk(file_dir):
# print(root) #当前目录路径
# print(dirs) #当前路径下所有子目录
# print(files) #当前路径下所有非目录子文件
for file in files:
if re.match(format_name, file):
print(os.path.join(root, file))
os.remove(os.path.join(root, file))


remove_specified_format_file(r'D:\学习\LDC\java', r'\._*')

11、计算文件总数

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


def file_count(file_dir):
"""

:param file_dir: 文件根目录
:return:
"""
count = 0
for root, dirs, files in os.walk(file_dir):
# print(root) #当前目录路径
# print(dirs) #当前路径下所有子目录
# print(files) #当前路径下所有非目录子文件
count += len(files)
return count


print(file_count(r'D:\学习\LDC\java\Java学习\newEstore\estore\js'))

12、计算文件夹大小

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

def file_size(file_dir):
"""
删除指定格式的文件
:param file_dir: 文件根目录
:return:
"""
size = 0
for root, dirs, files in os.walk(file_dir):
# print(root) #当前目录路径
# print(dirs) #当前路径下所有子目录
# print(files) #当前路径下所有非目录子文件
for file in files:
size += os.path.getsize(os.path.join(root, file))
# M为单位
return size / 1024 / 1024


file_name = r'D:\学习'
print(file_size(file_name))

13、时间格式字符串相减

1
2
3
4
5
6
7
8
9
10
11
12
import datetime
import time

start = str(datetime.datetime.now())[:19]
time.sleep(60)
end = str(datetime.datetime.now())[:19]
print(start,end)
link_start = datetime.datetime.strptime(start, '%Y-%m-%d %H:%M:%S')
link_end = datetime.datetime.strptime(end, '%Y-%m-%d %H:%M:%S')
link_min = round((link_end - link_start).seconds / 60, 2)
print(link_min,'分钟')

14、显示循环进度条

参考:https://blog.csdn.net/zejianli/article/details/77915751

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
from tqdm import tqdm,trange
from time import sleep
text = ""
for char in tqdm(["a", "b", "c", "d"]):
text = text + char
sleep(1)


# 方式二
import time


def process_bar(percent, index, total,start_time, start_str='', end_str='', total_length=100):
# 进度条
percent_length = int(percent)
bar = '\r' + start_str + ('\033[1;31;41m \033[0m' * percent_length + '\033[1;37;47m \033[0m' * (
total_length - percent_length)) + f' {round(index / total * 100, 2)}% ' + f' {index}|{end_str}'+ f' |已进行时间: {round(time.time() - start_time, 2)}秒'

print(bar, end='', flush=True)


if __name__ == '__main__':
data_set = [i for i in range(23)]
i = 0
start_time = time.time()
total = len(data_set)
end_str = '{}'.format(total)
for data in data_set:
time.sleep(1)
i += 1
process_bar(i * 100 / total, i, total, start_time, start_str='', end_str=end_str, total_length=100)

# 方式三
import sys
import time

d = [i for i in range(100)]
for i in range(len(d)):
time.sleep(1)
sys.stdout.write('\r>> Downloading %.2f%%' % (float(i) / float(len(d)) * 100.0))
sys.stdout.flush()

15、把列表中的字典转成csv文件

1
2
3
4
5
6
import pandas as pd
lists = [{'a':1,'b':2},{'a':2,'b':3}]
df = pd.DataFrame(lists)
print(df)
df.to_csv('result2.csv')

16、linux根据端口杀进程

1
2
3
4
5
6
7
8
9
10
11
12
import os


def killport(port):
command = '''kill -9 $(netstat -nlp | grep :''' + str(port) + ''' | awk '{print $7}' | awk -F"/" '{ print $1 }')'''
os.system(command)


# 开始执行
if __name__ == '__main__':
port = 4237
killport(port)

17、判断是什么系统

1
2
3
4
5
6
import platform
PlATFORM = platform.system()
if PlATFORM == "Linux":
print('linux')
else:
print('其他')

18、日志输出模块

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
import logging
import platform
# 全局函数
PlATFORM = platform.system()
if (PlATFORM == "Linux"):
# linux系统,文件保存在var下
SERVER_LOG_PATH = '/var/mylog.log'
else:
# windows系统,文件保存在D盘下
SERVER_LOG_PATH = 'D:\mylog.log'
# 定义一个logging的对象,命名为mylog
LOGGER = logging.getLogger('mylog')
# 设置级别为WARNING
LOGGER.setLevel(logging.WARNING)
# 创建一个handler,用于写入日志文件
fh = logging.FileHandler(SERVER_LOG_PATH, encoding='utf-8')
fh.setLevel(logging.WARNING)
# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
fh.setFormatter(formatter)
# 给Logger添加handler
LOGGER.addHandler(fh)
# 不在控制台显示
LOGGER.propagate = False

19、字典排序

字典在内存中发布是无序的,当想对键值或者键名进行排序时可以先把字典转成元组,这可以达到排序的目的。

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
score = {'小明': {'avg_score': 90, 'English': 90, 'Math': 90, 'Chniese': 90, },
'小红': {'avg_score': 60, 'English': 60, 'Math': 61, 'Chniese': 59, },
'小黑': {'avg_score': 70, 'English': 75, 'Math': 65, 'Chniese': 70, },
'小白': {'avg_score': 80, 'English': 95, 'Math': 65, 'Chniese': 80, },
}
# 对姓名进行排序,即对键名进行排序
b = sorted(score.items(), key=lambda x: x[0], reverse=True)
show_str = ''
for info in b:
# print(info)
key, value = info[0], info[1]
show_str += '姓名:{},平均分:{},成绩:{}'.format(key,value['avg_score'], value) + '\r\n'
print('对姓名进行排序')
print(show_str)
# 对平均分进行排序
b = sorted(score.items(), key=lambda x: x[1]['avg_score'], reverse=True)
show_str = ''
for info in b:
# print(info)
key, value = info[0], info[1]
show_str += '姓名:{},平均分:{},成绩:{}'.format(key,value['avg_score'], value) + '\r\n'
print('对平均分进行排序')
print(show_str)

# 对英语成绩进行排序
b = sorted(score.items(), key=lambda x: x[1]['English'], reverse=True)
show_str = ''
for info in b:
# print(info)
key, value = info[0], info[1]
show_str += '姓名:{},平均分:{},成绩:{}'.format(key,value['avg_score'], value) + '\r\n'
print('对英语成绩进行排序')
print(show_str)

输出:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
对姓名进行排序
姓名:小黑,平均分:70,成绩:{'avg_score': 70, 'English': 75, 'Math': 65, 'Chniese': 70}
姓名:小红,平均分:60,成绩:{'avg_score': 60, 'English': 60, 'Math': 61, 'Chniese': 59}
姓名:小白,平均分:80,成绩:{'avg_score': 80, 'English': 95, 'Math': 65, 'Chniese': 80}
姓名:小明,平均分:90,成绩:{'avg_score': 90, 'English': 90, 'Math': 90, 'Chniese': 90}

对平均分进行排序
姓名:小明,平均分:90,成绩:{'avg_score': 90, 'English': 90, 'Math': 90, 'Chniese': 90}
姓名:小白,平均分:80,成绩:{'avg_score': 80, 'English': 95, 'Math': 65, 'Chniese': 80}
姓名:小黑,平均分:70,成绩:{'avg_score': 70, 'English': 75, 'Math': 65, 'Chniese': 70}
姓名:小红,平均分:60,成绩:{'avg_score': 60, 'English': 60, 'Math': 61, 'Chniese': 59}

对英语成绩进行排序
姓名:小白,平均分:80,成绩:{'avg_score': 80, 'English': 95, 'Math': 65, 'Chniese': 80}
姓名:小明,平均分:90,成绩:{'avg_score': 90, 'English': 90, 'Math': 90, 'Chniese': 90}
姓名:小黑,平均分:70,成绩:{'avg_score': 70, 'English': 75, 'Math': 65, 'Chniese': 70}
姓名:小红,平均分:60,成绩:{'avg_score': 60, 'English': 60, 'Math': 61, 'Chniese': 59}

20、对列表中字典按多个键值排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from operator import itemgetter
data = [
{'code': 1, 'position': 300, 'time': '1620442242'},
{'code': 2, 'position': 255, 'time': '1620442242'},
{'code': 3, 'position': 256, 'time': '1620442242'},
{'code': 1, 'position': 500, 'time': '1620442242'},
{'code': 5, 'position': 455, 'time': '1620442242'},
{'code': 1, 'position': 322, 'time': '1620442242'},
{'code': 6, 'position': 676, 'time': '1620442242'},
]
data = sorted(data, key=itemgetter('code', 'position'))

print(data)

输出:

1
2
3
4
5
6
7
8
[
{'code': 1, 'position': 300, 'time': '1620442242'},
{'code': 1, 'position': 322, 'time': '1620442242'},
{'code': 1, 'position': 500, 'time': '1620442242'},
{'code': 2, 'position': 255, 'time': '1620442242'},
{'code': 3, 'position': 256, 'time': '1620442242'},
{'code': 5, 'position': 455, 'time': '1620442242'},
{'code': 6, 'position': 676, 'time': '1620442242'}]

21、时间格式与字符串互转、比较大小

1
2
3
4
5
6
7
8
9
10
import datetime

# 当前时间转字符串
now = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
# 字符串转时间格式
now = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
a = now + datetime.timedelta(minutes=-15)
# 时间比较大小
if a < now:
print('yes')

22、python把’\u’开头的字符串转中文

1
2
3
4
5
6
7
str_data = '\\u7528\\u6237 ID \\u6216\\u5bc6\\u7801\\u9519\\u8bef'
# 字符串.encode('utf-8').decode('unicode_escape')
str_data_to_zh = str_data.encode('utf-8').decode('unicode_escape')
print(str_data_to_zh)

# 输出
用户 ID 或密码错误

23、python翻译模块

可以把英文翻译成中文,也可以把中文翻译成英文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#pip install  translate

from translate import Translator

name = 'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca'
translator = Translator(to_lang="chinese")
translation = translator.translate(name)
print(translation)

translator= Translator(from_lang="chinese",to_lang="english")
translation = translator.translate("我想你")
print(translation)


#输出:
#
#大熊猫,熊猫,熊猫熊,浣熊,大熊猫
#I missed you.

24、python实现字符串转字典

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

target_str = '{"h": 1, "e": 2, "l": 3, "l": 4, "o": 5}'
target_str2 = "{'h': 1, 'e': 2, 'l': 3, 'l': 4, 'o': 5}"

# 方式1:使用json,缺点,字符串中不能出现单引号
# 由于 json 语法规定 数组或对象之中的字符串必须使用双引号,不能使用单引号
# 官网https://www.json.org/json-en.html上有一段描述是
# A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes
print(json.loads(target_str))
# print(json.loads(target_str2)) # 使用json转这个字符串会报错 Expecting property name enclosed in double quotes

# 方式2:使用eval函数,缺点,不安全
print(eval(target_str))
print(eval(target_str2))
# print(eval("__import__('os').system('dir')")) # 会列出当前的目录文件,如果字符串是一些删除命令,则可以把整个目录清空!

# 方式3,使用ast.literal_eval,没有json与eval的缺点,推荐使用这个
print(ast.literal_eval(target_str))
print(ast.literal_eval(target_str2))

输出:

1
2
3
4
5
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
{'h': 1, 'e': 2, 'l': 4, 'o': 5}
{'h': 1, 'e': 2, 'l': 4, 'o': 5}

25、使用python给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
import openpyxl, sys

wb = openpyxl.load_workbook('b.xlsx')
sheet = wb['Sheet1']

# 在excel表格第二行添加新数据
addrow = 1 # 增加一行
row = 2 # 在第二行新增一行
name = 'b-back.xlsx' # 新的表名

wb1 = openpyxl.Workbook()
sheet1 = wb1['Sheet']

# 复制前row行
for i in range(1, row):
for j in range(1, sheet.max_column + 1):
sheet1.cell(row=i, column=j).value = sheet.cell(row=i, column=j).value


# 复制后row行
for i in range(row, sheet.max_row + 1):
for j in range(1, sheet.max_column + 1):
if i == row:
# 给第row行添加新的数据
sheet1.cell(row=row, column=j).value = '新增'
sheet1.cell(row=i + addrow, column=j).value = sheet.cell(row=i, column=j).value

wb1.save(name)

在这里插入图片描述

__END__