判断路径中是否包含中文

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. leetcode203. 移除链表元素

    方法一(删除头结点时另做考虑) class Solution { public: ListNode* removeElements(ListNode* head, int val) { if(head ...

  2. html表格及列表

    表格的属性: border:边框 cellpadding:内边距  单元格边框跟内容之间的间距 cellspacing:外边距  单元格跟单元格之间的距离 align:表格的对其样式 width:宽度 ...

  3. SQL中group by的注意事项

    最最最最重要的: group by有一个原则,就是select后面所有的列中,没有使用聚合函数的列,必须出现在group by子句中. group by子句中的注意事项: 1,不能使用别名(因为执行顺 ...

  4. Python爬虫练习

    例一:爬取信息关于'gbk' codec can't encode character '\xa0' in position 6: illegal 错误提示: #初始化class 得到对象 draw= ...

  5. 禁用Chrome的“请停用以开发者模式运行的扩展程序”提示

    1.前言 每次启动都会有一个烦人的“请停用以开发者模式运行的扩展程序”提示,这个提示有多烦人,接触过的人都知道,启动的时候它不立即提示,等过了几秒钟等你打开某个网页开始执行某些操作时它突然弹出来干扰你 ...

  6. SpringBoot集成Spring Security(1)——入门程序

    因为项目需要,第一次接触 Spring Security,早就听闻 Spring Security 功能强大但上手困难,学习了几天出入门道,特整理这篇文章希望能让后来者少踩一点坑(本文附带实例程序,请 ...

  7. Jenkins使用过程中遇到的问题

    1./usr/local/jdk1.8.0_191/ is not a directory on the Jenkins master (but perhaps it exists on some a ...

  8. 手把手教你 通过 NuGet.Server 包 搭建nuget服务器,并使用桌面工具上传 nuget 包,免命令行

    新建web项目 工具:VS2013 版本:.Net Framework 4.6,低版本也行,不过要找到对应版本的Nuget.Server 装了NuGet客户端(百度如何安装) WebForm或MVC都 ...

  9. torch_06_卷积神经网络

    1.概述 卷积神经网络的参数,由一些可学习的滤波器集合构成的,每个滤波器在空间上都计较小,但是深度和输入数据的深度保持一致.在前向传播中,让每个滤波器都在输入数据的宽度和高度上滑动(卷积),然后计算整 ...

  10. Java解压和压缩带密码的zip或rar文件(下载压缩文件中的选中文件、向压缩文件中新增、删除文件)

    JAVA 实现在线浏览管理zip和rar的工具类 (有密码及无密码的)以及下载压缩文件中的选中文件(向压缩文件中新增.删除文件) 这是之前的版本 JAVA 解压压缩包中指定文件或实现压缩文件的预览及下 ...