判断路径中是否包含中文

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:日常应用汇总的更多相关文章

  1. python日常-list and dict

    什么是list: list 觉得算是python日常编程中用的最多的python自带的数据结构了.但是python重的list跟其他语言中的并不相同. 少年..不知道你听说过python中的appen ...

  2. redis日常使用汇总--持续更新

    redis日常使用汇总--持续更新 工作中有较多用到redis的场景,尤其是触及性能优化的方面,传统的缓存策略在处理持久化和多服务间数据共享的问题总是不尽人意,此时引入redis,但redis是单线程 ...

  3. Kettle日常使用汇总整理

    Kettle日常使用汇总整理 Kettle源码下载地址: https://github.com/pentaho/pentaho-kettle Kettle软件下载地址: https://sourcef ...

  4. Python IDLE快捷键汇总

    Python IDLE快捷键汇总 在Options→configure IDLE→keys,查看现存的快捷键,也可以配置选择快捷 编辑状态时: Ctrl+Shift+space(默认与输入法冲突,修改 ...

  5. PYTHON资源入口汇总

    Python资源入口汇总 官网 官方文档 教程和书籍 框架 数据库 模板 工具及第三方包 视频 书籍 博客 经典博文集合 社区 其他 整理中,进度30% 官网 入口 官方文档 英文 document ...

  6. python 2 与python 3区别汇总

    python 2 与python 3区别汇总 一.核心类差异1. Python3 对 Unicode 字符的原生支持.Python2 中使用 ASCII 码作为默认编码方式导致 string 有两种类 ...

  7. 一份超全的Python学习资料汇总

    一.学习Python必备技能图谱二.0基础如何系统学习Python?一.Python的普及入门1.1 Python入门学习须知和书本配套学习建议1.2 Python简史1.3 Python的市场需求及 ...

  8. [Python] 学习资料汇总

    Python是一种面向对象的解释性的计算机程序设计语言,也是一种功能强大且完善的通用型语言,已经有十多年的发展历史,成熟且稳定.Python 具有脚本语言中最丰富和强大的类库,足以支持绝大多数日常应用 ...

  9. Python面试题汇总

    原文:http://blog.csdn.net/jerry_1126/article/details/44023949 拿网络上关于Python的面试题汇总了,给出了自认为合理的答案,有些题目不错,可 ...

随机推荐

  1. ros wifi把信号弱的客户端踢出去的脚本

    以下脚本为小于75强度的都踢出去 非capman脚本: /interface wireless registration-table :do {:foreach i in=[find] do={:lo ...

  2. Loj #2529. 「ZJOI2018」胖

    Loj #2529. 「ZJOI2018」胖 题目描述 Cedyks 是九条可怜的好朋友(可能这场比赛公开以后就不是了),也是这题的主人公. Cedyks 是一个富有的男孩子.他住在著名的 The P ...

  3. StuQ技能图谱

  4. MarkDown的一些基本语法

    Markdown是一种可以使用普通文本编辑器编写的标记语言,通过简单的标记语法,它可以使普通文本内容具有一定的格式. Markdown的语法简洁明了.学习容易,而且功能比纯文本更强,因此有很多人用它写 ...

  5. Spring-Boot-操作-Redis,三种方案全解析!

    在 Redis 出现之前,我们的缓存框架各种各样,有了 Redis ,缓存方案基本上都统一了,关于 Redis,松哥之前有一个系列教程,尚不了解 Redis 的小伙伴可以参考这个教程: Redis 教 ...

  6. VB.net 通过句柄操作其他窗口

    Imports System.TextImports System.Runtime.InteropServices Public Class Form1    ' 相关API函数声明,注释掉的这里没用 ...

  7. docker部署angular和asp.net core组成的前后端分离项目

    最近使用docker对项目进行了改进,把步骤记录一下,顺便说明一下项目的结构. 项目是前后端分离的项目,后端使用asp.net core 2.2,采用ddd+cqrs架构的分层思想,前端使用的是ang ...

  8. vertx 异步编程指南 step8-使用RxJava进行反应式编程

    vertx 异步编程指南 step8-使用RxJava进行反应式编程 2018-04-23 13:15:32 zyydecsdn 阅读数 1212  收藏 更多 分类专栏: vertx   到目前为止 ...

  9. 关于.Net Core 前后端分离跨域请求时 ajax并发请求导致部分无法通过验证解决办法。

    项目中有这样一个页面.页面加载的时候会同时并发6个ajax请求去后端请求下拉框. 这样会导致每次都有1~2个“浏览器预请求”不通过. 浏览器为什么会自动发送“预请求”?请看以面连接 https://b ...

  10. python 绘图与可视化 Graphviz 二叉树 、 error: Microsoft Visual C++ 14.0 is required

    需要对二叉树的构建过程进行可视化,发现了这个Graphviz软件,他对描绘数据间的关系十分擅长. 下载链接:https://graphviz.gitlab.io/_pages/Download/Dow ...