获取目录 运行目录(cmd) 1 2 import oscmd=os.getcwd()
Py文件目录 1 2 import ospy=os.path.dirname(os.path.abspath(__file__))
EXE文件目录 1 2 import sys print(sys.executable)
运行结果(.py)
1 C:\Users\28734\AppData\Local\Programs\Python\Python39\python.exe
故在非EXE中调试时,获取的是Python.exe所在位置
获取某文件的文件名并拆分 1 2 3 4 5 6 7 8 9 import osfile='E:\...\xxx.jpg' filedir=os.path.split(file) filename=filedir[1 ] file=filename.split('.' ) name=file[0 ] houzui=file[1 ]
拆分字符串 1 2 a='123456.6543321.000000' a1=a.split('.' )
当前时间获取 1 2 3 import datetimetime = datetime.datetime.now() realtime = time.strftime("%Y-%m-%d" )
计算时间差 1 2 3 4 from dateutil import parserd1 = '2021-01-01' d2 = '2021-02-01' days = str ((parser.parse(d2) - parser.parse(d1)).days)
从XML提取信息 temp.xml
:
未经格式化:
1 <?xml version="1.0" encoding="utf-8" ?> <images > <image > <startdate > 20210813</startdate > <fullstartdate > 202108130900</fullstartdate > <enddate > 20210814</enddate > <url > /th?id=OHR.UbehebeCrater_ZH-CN0157876978_1920x1080.jpg& rf=LaDigue_1920x1080.jpg& pid=hp</url > <urlBase > /th?id=OHR.UbehebeCrater_ZH-CN0157876978</urlBase > <copyright > 死亡谷国家公园里的优比喜比火山口,加利福尼亚州 (© Albert Knapp/Alamy)</copyright > <copyrightlink > https://www.bing.com/search?q=%E6%AD%BB%E4%BA%A1%E8%B0%B7%E5%9B%BD%E5%AE%B6%E5%85%AC%E5%9B%AD& form=hpcapt& mkt=zh-cn</copyrightlink > <headline > </headline > <drk > 1</drk > <top > 1</top > <bot > 1</bot > <hotspots > </hotspots > </image > <tooltips > <loadMessage > <message > 正在加载...</message > </loadMessage > <previousImage > <text > 上一个图像</text > </previousImage > <nextImage > <text > 下一个图像</text > </nextImage > <play > <text > 播放视频</text > </play > <pause > <text > 暂停视频</text > </pause > </tooltips > </images >
经格式化
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 <images > <image > <startdate > 20210813</startdate > <fullstartdate > 202108130900</fullstartdate > <enddate > 20210814</enddate > <url > /th?id=OHR.UbehebeCrater_ZH-CN0157876978_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp</url > <urlBase > /th?id=OHR.UbehebeCrater_ZH-CN0157876978</urlBase > <copyright > 死亡谷国家公园里的优比喜比火山口,加利福尼亚州 (© Albert Knapp/Alamy)</copyright > <copyrightlink > https://www.bing.com/search?q=%E6%AD%BB%E4%BA%A1%E8%B0%B7%E5%9B%BD%E5%AE%B6%E5%85%AC%E5%9B%AD&form=hpcapt&mkt=zh-cn</copyrightlink > <headline /> <drk > 1</drk > <top > 1</top > <bot > 1</bot > <hotspots /> </image > <tooltips > <loadMessage > <message > 正在加载...</message > </loadMessage > <previousImage > <text > 上一个图像</text > </previousImage > <nextImage > <text > 下一个图像</text > </nextImage > <play > <text > 播放视频</text > </play > <pause > <text > 暂停视频</text > </pause > </tooltips > </images >
Python源码:
1 2 3 4 5 6 from xml.dom import minidomdom=minidom.parse("temp.xml" ) root=dom.documentElement msg = root.getElementsByTagName('copyright' ) information1 = msg[0 ].firstChild.data print ('拍摄地(作者):' ,information1)
多线程运行任务 1 2 3 4 5 6 from threading import Thread t1 = Thread(target=first) t2 = Thread(target=sec) t1.start() t2.start()
给图片插入句子 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import cv2from PIL import ImageFont, ImageDraw, Imageimport numpy as np bk_img= cv2.imread("first.jpg" ) word = 'Hello world' fontpath= "HarmonyOS_Sans_SC_Black.ttf" font= ImageFont.truetype(fontpath,32 ) img_pil= Image.fromarray(bk_img) draw= ImageDraw.Draw(img_pil) draw.text((70 ,230 ), word, font= font, fill= (0 ,0 ,0 )) bk_img= np.array(img_pil) cv2.imshow("finally" ,bk_img) cv2.waitKey() cv2.imwrite("finally.jpg" ,bk_img)
打开指定网站 1 2 3 import webbrowserurl = 'https://muspace.top' webbrowser.open_new(url)
注册表 1 2 3 4 5 6 7 8 import win32apiimport win32conkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE,'SYSTEM\CurrentControlSet\Control\Session Manager\Memory Management\PrefetchParameters' ,0 , win32con.KEY_ALL_ACCESS) win32api.RegCreateKey(key,'{2227A280-3AEA-1069-A2DE-08002B30309D}' ) win32api.RegSetValueEx(key,'EnablePrefetcher' ,0 ,win32con.REG_SZ,'00000001' )
随机从txt中读取值 1 2 3 4 5 6 7 8 9 def txt (): import random with open ('sen.txt' , 'r' , encoding='utf8' ) as f: datas = f.readlines() data = random.choice(datas) if data.strip() == '' : txt() else : return data.strip()
查找图片并扫描其二维码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 import numpy as npfrom PIL import Imagefrom pyzbar import pyzbarimport globimport osimport sysPATH_TO_TEST_IMAGES_DIR = os.path.dirname(os.path.abspath(__file__)) img=PATH_TO_TEST_IMAGES_DIR + "/*.[jp][pn]g" for pidImage in glob.glob(img): print ('要解析二维码的图片: ' ,pidImage) im = np.array(Image.open (pidImage)) try : print (pyzbar.decode(im)[0 ].data.decode("utf-8" )) os.remove(pidImage) print ('识别完毕,自动移除二维码' ) except : print ('无法识别二维码,请检查你的图片是否正确或确认程序根目录中含有图片' )
图片转码 1 2 3 4 from PIL import Image pidImage='xxx.jpg' im = Image.open (pidImage).convert('RGB' ) im.save(newfilename,'webp' )
使用字典方法实现switch,改掉叠if杀人书的习惯
From:Python那些优雅的写法:switch-case - 简书 (jianshu.com)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 switch = { "a" :lambda :x:x*2 , "b" :lambda :x:x*3 , "c" :lambda :x:x**x } try : swtich["c" ](6 ) except KeyError as e: pass
进度条显示 1 2 3 from tqdm import tqdmfor i in tqdm(range (100000 )):
解压zip压缩包 1 2 3 import zipfilewith zipfile.ZipFile(zipname) as zf: zf.extractall()
遍历文件夹中的所有文件并重命名 1 2 3 4 5 for file in os.listdir(imgdir): newname=file+'.jpg' new_name=file.replace(file,newname) os.renames(os.path.join(imgdir,file),os.path.join(imgdir,new_name))
requirements.txt 用于指示程序所用第三方库
生成 1 2 3 4 pip install pipreqs pipreqs . --encoding =utf8 --force
使用 1 pip install -r requirements.txt
管理员权限获取 注意: 无法在Debug中调试该项,请直接通过文件运行
1 2 3 4 if ctypes.windll.shell32.IsUserAnAdmin(): else : ctypes.windll.shell32.ShellExecuteW(None , "runas" , sys.executable, __file__, None , 1 )