判断路径中是否包含中文

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. 每天一道Rust-LeetCode(2019-06-04)

    每天一道Rust-LeetCode(2019-06-04) 最长回文子串 坚持每天一道题,刷题学习Rust. 原题 题目描述 给定一个字符串 s,找到 s 中最长的回文子串.你可以假设 s 的最大长度 ...

  2. 实现一个new操作符

    new 操作符做了这些事: 1.它创建了一个全新的对象: 2.它会被执行[[Prototype]](也就是__proto__)链接: 3.它使this指向新创建的对象: 4.通过new创建的每个对象最 ...

  3. ESP8266 LUA脚本语言开发: 准备工作-LUA开发说明

    前言 开发Lua需要使用这个软件 注:该软件需要按照JDK  即 JAVA虚拟机,如果没有安装过JDK,请先看JDK安装教程安装JDK USB线连接开发板接入电脑 选择自己的串口号 波特率115200 ...

  4. 字段加密实践(django-fernet-fields)

    一.fernet介绍 Fernet 用于django模型字段对称加密,使用 crytography 库. 官网帮助文档 1.先决条件 django-fernet-fields 支持Django 1.8 ...

  5. 用Python搞定九宫格式的朋友圈。内附“马云”朋友圈

    PIL(Python Imaging Library)是一个非常强大的Python库,但是它支持Python2.X, 在Python3中则使用的是Pillow库,它是从PIL中fork出来的一个分支. ...

  6. Java 获取所有子类信息

    我以前的博客(Java Scala获取注解的类信息)介绍过通过Reflections工具通过使用特定注解的类的信息,其实本工具也可以获取接口,抽象类,类等的所有子类信息.使用方法如下: Reflect ...

  7. Intellij插件之Alibaba Java Coding Guidelines

    作用: 阿里巴巴出品的java代码规范插件,可以扫描整个项目找到不规范的地方 并且大部分可以自动修复 .虽说检测功能没有findbugs强大,但是可以自 动修复,阿里巴巴Java编码指南插件支持. 插 ...

  8. 云服务器、VPS、虚拟主机三者之间的区别?

    更多精彩内容欢迎访问我的个人博客皮皮家园:https://www.zh66.club期待您的光临哦!我是皮皮猪,感谢各位光临,能为您排忧解难小站深感荣幸!祝您生活愉快! 什么是虚拟主机? 同云主机不一 ...

  9. MySQL事务未提交导致整个表锁死

    问题及说明: 当一个SQL事务执行完了,但未COMMIT,后面的SQL想要执行就是被锁,超时结束:报错信息如下: mysql> ERROR 1205 (HY000): Lock wait tim ...

  10. HTML+css基础 表格标签table Table标签属性 td标签属性

    表格标签table:   他是由行与列构成,最小单位是单元格. 行标签  <tr></tr> 单元格标签<td></td> Table标签属性: Bor ...