Python:日常应用汇总
判断路径中是否包含中文
import re
def IsContainChinese(path:str) -> bool :
cnPatter=re.compile(u'[\u4e00-\u9fa5]+')
match=cnPatter.search(path)
flag=False
if match:
flag=True
else:
flag = False
return flag
将文件保存为csv格式
import csv
def WriteResultToCSV(**kwags):
v = [ v for v in kwags.values()]
# v=lambda v:[ v for v in kwags.values()]
# print(v)
for item in v:
try:
header=["文件名","高度","宽度"]
# 如果不加newline参数,则保存的csv文件会出现隔行为空的情况
with open(os.getcwd()+"\\result.csv",'w+',newline="") as fw:
csvWriter=csv.writer(fw)
csvWriter.writerow(header)
# print(item.items())
for k,v in item.items():
print(f"{k} {v}")
csvWriter.writerow([k,str(v[0]),str(v[1])])
except Exception as e:
pass
获取图片分辨率
- 方法一:通过opencv该方法不支持路径或文件名含有中文
python opencv2安装: pip install opencv-python
import cv2
def GetResolution(path,imgList):
temDict={}
for item in imgList:
# opencv 不支持中文路径
img=cv2.imread(path+"\\"+item)
# cv2.namedWindow("Image")
# cv2.imshow("Image",img)
# cv2.waitKey(1)
# cv2.destroyAllWindows()
imgResolution=img.shape
temDict[item]=imgResolution
return temDict
- 方法二:通过opencv
import cv2
import numpy as np
# 使用该方法时,路径中可含有中文,其中tmp为完整的图片路径
img=cv2.imdecode(np.fromfile(tmp,dtype=np.uint8),cv2.IMREAD_COLOR)
# 获取图片高度和宽度
imgHeight,imgWidth=img.shape[:2]
- 方法三:通过Pillow
pip install Pillow
from PIL import Image
def GetImgSize(path):
"""
path:传入完整路径
"""
img=Image.open(path)
imgWidth,imgHeight=img.size
获取文件夹内特定的文件
import os
def GetImgList(path):
imgList=[ img for img in os.listdir(path)
if os.path.isfile(os.path.join(path,img)) and (img.endswith(".jpg") or img.endswith(".jpge") or img.endswith(".png"))
]
return imgList
将图片转换为Base64编码
import base64
def ConverImgToBase64(path,imgList):
resultList={}
for img in imgList:
try:
with open (path+"\\"+img,'rb') as fr:
data=base64.b64encode(fr.read())
tempResult=data.decode()
resultList[img]=tempResult
except Exception as e:
resultList["Exception"]=e
return resultList
生成MD5码
# 生成MD5码
def GenerateMD5Code(sku,secretKey='e10adc3949ba59abbe56e057f20f883e'):
md5=hashlib.md5()
encodeStr=secretKey+sku
md5.update(encodeStr.encode('utf8'))
return md5.hexdigest()
判断文件或文件夹是否存在
import os
def IsExistFile(path):
try:
if (os.path.exists(path)):
os.remove(path)
except Exception as identifier:
pass
比较文件差异
import os
# 描述信息:一个文件夹内一张图片对应一个xml或者只有图片或只有xml
def ListFile(path):
imgList=[]
xmlList=[]
extendIsXmlCount=0
extendIsImgCount=0
for file in os.listdir(path):
fileList=file.split(".")
try:
if fileList[-1] == "xml":
extendIsXmlCount+=1
xmlList.append(fileList[0])
elif fileList[-1] == "jpg" or fileList[-1] == "jpeg" or fileList[-1] == "png":
extendIsImgCount+=1
imgList.append(fileList[0])
except Exception as e:
print("error")
differenceResult=set(imgList+xmlList)
return imgList,xmlList,extendIsImgCount,extendIsXmlCount,differenceResult
def CompareCount(xmlCount,imgCount):
'''
-1: xml > img
0 : xml == img
1 : xml < img
'''
# compareResult=-9999
differenceCount=-9999
if (xmlCount > imgCount):
# print(f"xml Count {xmlCount} is more than img Count {imgCount} ,difference is {xmlCount-imgCount}")
compareResult=f"xml Count {xmlCount} is more than img Count {imgCount} ,difference is {xmlCount-imgCount}"
differenceCount=xmlCount-imgCount
elif(xmlCount < imgCount):
# print(f"xml Count {xmlCount} is less than img Count {imgCount} ,difference is {imgCount-xmlCount}")
compareResult=f"xml Count {xmlCount} is less than img Count {imgCount} ,difference is {imgCount-xmlCount}"
differenceCount=imgCount-xmlCount
elif (xmlCount == imgCount):
# print(f"xml Count {xmlCount} is equal img Count {imgCount} ,difference is {imgCount-xmlCount}")
compareResult=f"xml Count {xmlCount} is equal img Count {imgCount} ,difference is {imgCount-xmlCount}"
differenceCount=imgCount-xmlCount
return compareResult,differenceCount
def RemoveDuplicateItem(ListA,ListB):
tempSetA=set(ListA)
tempSetB=set(ListB)
if len(tempSetA) >= len(tempSetB):
result=tempSetA-tempSetB
else:
result=tempSetB-tempSetA
return result
读取pkl文件
import pickle
def ReadFile(path):
result=""
try:
with open (path,'rb') as fr:
result=pickle.load(fr)
except Exception as e:
result=e
return result
存取为pkl文件
import pickle
def WriteStrToLogFile(path,dataStr):
for i in range(2,5):
PickleToFile(path+"\\"+"error"+str(i)+".pkl",dataStr)
def PickleToFile(path,fileName):
with open(path,'wb') as fw:
pickle.dump(dataStr,fw)
将时间转换为Unix时间戳
import time
import datetime
def ChangDateTimeToUnix(inputDateTime):
'''
将标准时间转换为Unix时间戳
time strptime() 函数根据指定的格式把一个时间字符串解析为时间元组
time.strptime(string[, format])
'''
timeArray = time.strptime(inputDateTime, "%Y-%m-%d %H:%M:%S")
timeStamp = int(time.mktime(timeArray))
return timeStamp
本文同步在微信订阅号上发布,如各位小伙伴们喜欢我的文章,也可以关注我的微信订阅号:woaitest,或扫描下面的二维码添加关注:

Python:日常应用汇总的更多相关文章
- python日常-list and dict
什么是list: list 觉得算是python日常编程中用的最多的python自带的数据结构了.但是python重的list跟其他语言中的并不相同. 少年..不知道你听说过python中的appen ...
- redis日常使用汇总--持续更新
redis日常使用汇总--持续更新 工作中有较多用到redis的场景,尤其是触及性能优化的方面,传统的缓存策略在处理持久化和多服务间数据共享的问题总是不尽人意,此时引入redis,但redis是单线程 ...
- Kettle日常使用汇总整理
Kettle日常使用汇总整理 Kettle源码下载地址: https://github.com/pentaho/pentaho-kettle Kettle软件下载地址: https://sourcef ...
- Python IDLE快捷键汇总
Python IDLE快捷键汇总 在Options→configure IDLE→keys,查看现存的快捷键,也可以配置选择快捷 编辑状态时: Ctrl+Shift+space(默认与输入法冲突,修改 ...
- PYTHON资源入口汇总
Python资源入口汇总 官网 官方文档 教程和书籍 框架 数据库 模板 工具及第三方包 视频 书籍 博客 经典博文集合 社区 其他 整理中,进度30% 官网 入口 官方文档 英文 document ...
- python 2 与python 3区别汇总
python 2 与python 3区别汇总 一.核心类差异1. Python3 对 Unicode 字符的原生支持.Python2 中使用 ASCII 码作为默认编码方式导致 string 有两种类 ...
- 一份超全的Python学习资料汇总
一.学习Python必备技能图谱二.0基础如何系统学习Python?一.Python的普及入门1.1 Python入门学习须知和书本配套学习建议1.2 Python简史1.3 Python的市场需求及 ...
- [Python] 学习资料汇总
Python是一种面向对象的解释性的计算机程序设计语言,也是一种功能强大且完善的通用型语言,已经有十多年的发展历史,成熟且稳定.Python 具有脚本语言中最丰富和强大的类库,足以支持绝大多数日常应用 ...
- Python面试题汇总
原文:http://blog.csdn.net/jerry_1126/article/details/44023949 拿网络上关于Python的面试题汇总了,给出了自认为合理的答案,有些题目不错,可 ...
随机推荐
- leetcode 561. 数组拆分 I
为了理解这种方法,让我们从不同的角度来看待问题.我们需要形成数组元素的配对,使得这种配对中最小的总和最大.因此,我们可以查看选择配对中最小值的操作,比如 (a,b)(a,b) 可能会产生的最大损失 ...
- [LeetCode] 854. K-Similar Strings 相似度为K的字符串
Strings A and B are K-similar (for some non-negative integer K) if we can swap the positions of two ...
- 第02组 Alpha冲刺(4/6)
队名:無駄無駄 组长博客 作业博客 组员情况 张越洋 过去两天完成了哪些任务 摸鱼 提交记录(全组共用) 接下来的计划 沟通前后端成员,监督.提醒他们尽快完成各自的进度 学习如何评估代码质量 准备Al ...
- python总结十
1.代码int('20',8)的返回结果是:16 2.日志的统计和记录对于程序开发来说非常重要,python提供了非常好用的日志模块logging 3.元祖修改 4.python内置映射类型称为字典 ...
- Ubuntu安装微信、钉钉等各种windows软件
详见这个博客,用sudo dpkg -i 安装软件时,如果出现错误,是因为缺少安装依赖关系,用下面的命令解决: sudo apt-get install -f
- 团队作业第五次—项目冲刺-Day6
Day6 part1-SCRUM: 项目相关 作业相关 具体描述 所属班级 2019秋福大软件工程实践Z班 作业要求 团队作业第五次-项目冲刺 作业正文 hunter--冲刺集合 团队名称 hunte ...
- 推荐WEB 端批量移动设备管理控制工具STF
推荐WEB 端批量移动设备管理控制工具STF 1 官方网站 https://openstf.io/ 2 github https://github.com/openstf/stf 后面有时间了,抽空也 ...
- SQLAIchemy(二)ORM 相关
0. 前言 对象关系映射(Object Relational Mapping,简称ORM)模式是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术 简单的说,ORM是通过使用描述对象和数据库之 ...
- PHP获取cookie、Token、模拟登录、抓取数据、解析生成json
本文介绍使用PHP获取cookie,获取Token.以及模拟登录.然后抓取数据.最后解析生成json的的过程. 0. 设置Cookie路径 set_time_limit(0); //使用的cookie ...
- PyQt5笔记之菜单栏
目录 菜单栏 创建单层菜单 创建多层菜单 右键打开菜单 官方菜单实例 菜单常用方法 菜单栏 创建单层菜单 import sys from PyQt5.QtWidgets import QApplica ...