Python办公小工具

工具

Python 办公小工具

Github 下载地址

根据图片拖动目标

一天同事突然问到有没有办法在页面中一次性批量选中所有文件拖动进一个文件夹,碰巧页面没有开发这类全选的功能,只能一个个处理,于是尝试做了一下这个拖动小工具

前文

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
1.安装python3.4以上版本,并配置环境变量
教程:https://www.runoob.com/python3/python3-install.html
2.安装依赖包
方法:在cmd中(win+R  输入cmd  回车)输入
pip install pyperclip 回车
pip install xlrd 回车
pip install pyautogui==0.9.50 回车
pip install opencv-python 回车
pip install pillow 回车
3.把每一步要操作的图标、区域截图保存至本文件夹  png格式(注意如果同屏有多个相同图标,回默认找到最左上的一个,因此怎么截图,截多大的区域,是个学问,如输入框只截中间空白部分肯定是不行的,宗旨就是“唯一”)
4.在cmd.xls 的sheet1 中,配置每一步的指令,如指令类型1234  对应的内容填截图文件名,指令5对应的内容是等待时长(单位秒) 指令6对应的内容是滚轮滚动的距离,正数表示向上滚,负数表示向下滚
5.保存文件
6.双击waterRPA.py打开程序,按1表示excel中的指令执行一次,按2表示无限重复执行直到程序关闭
7.开始程序后请将程序框最小化,不然程序框挡住的区域是无法识别和操作的
8.如果程序开始后因为你选择了无限重复而鼠标被占用停不下来,alt+F4吧~


想自己开发和优化的  可以看看pyautogui库其他用法 https://blog.csdn.net/qingfengxd1/article/details/108270159

二次开发

流程:

  1. 根据"cmd.xls"作为数据库的思想,读取行数与内容
  2. 第一格输入数字代表模式,1 单击 2 双击 3 右键 4 输入 5 等待 6 滚轮 7 拖拽,第二格需要把从 A 拖曳到 B 的两个位置图标图片保存进文件夹中,并将名称保存到表格,第三格表示重复次数(-1 代表一直重复)
  3. 后台一直监听鼠标,当鼠标移到屏幕的左上角抛出 failSafeException 异常结束循环
展开代码
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import pyautogui
import time
import xlrd
import pyperclip


pyautogui.FAILSAFE = True # 启用自动防故障功能,左上角的坐标为(0,0),将鼠标移到屏幕的左上角,来抛出failSafeException异常


def mouseClick(clickTimes,lOrR,img,reTry):  #点击时间,左右键,图片名,重复次数
    if reTry == 1:
        while True:
            location = pyautogui.locateCenterOnScreen(img,confidence=0.9)
            if location is not None:
                pyautogui.click(location.x,location.y,clicks=clickTimes,interval=0.2,duration=0.2,button=lOrR)
                break
            print("未找到匹配图片,0.1秒后重试")
            time.sleep(0.1)
    elif reTry == -1:
        while True:
            print('循环')
            location=pyautogui.locateCenterOnScreen(img,confidence=0.9)
            print(location)
            if location is not None:
                pyautogui.click(location.x,location.y,clicks=clickTimes,interval=0.2,duration=0.2,button=lOrR)
            time.sleep(0.1)
    elif reTry > 1:
        i = 1
        while i < reTry + 1:
            location=pyautogui.locateCenterOnScreen(img,confidence=0.9)
            if location is not None:
                pyautogui.click(location.x,location.y,clicks=clickTimes,interval=0.2,duration=0.2,button=lOrR)
                print("重复")
                i += 1
            time.sleep(0.1)


def mainWork(img):
    i = 1
    while i < sheet1.nrows: #如果i小于总行数
        cmdType = sheet1.row(i)[0]
        if cmdType.value == 7.0:
            reTry = 1
            imglis = (sheet1.row(i)[1].value).split(",")
            img = imglis[0]
            img2 = imglis[1]
            #reTry为空单次
            location = pyautogui.locateCenterOnScreen(img,confidence=0.9)   #定位起始位置
            print(location)
            pyautogui.moveTo(location.x,location.y) #移动到图片坐标
            destination = pyautogui.locateCenterOnScreen(img2,confidence=0.9)    #目标图片图片
            print(destination)
            if location is not None:
                pyautogui.dragTo(destination.x,destination.y, button='left',duration=0.5)   #拖拽到目标位置
                print('拖拽',img+"到"+img2)


            #reTry不为空多次

            if sheet1.row(i)[2].ctype == 2 and sheet1.row(i)[2].value != 0: #第3列第2行非空
                #ctype :  0 empty,1 string, 2 number, 3 date, 4 boolean, 5 error
                reTry = sheet1.row(i)[2].value      #如果非空则赋值,回到循环小于等于i则退出循环
                for r in range(int(reTry),-1,-1):
                    location = pyautogui.locateCenterOnScreen(img,confidence=0.9)   #定位起始位置
                    print(location)
                    pyautogui.moveTo(location.x,location.y) #移动到图片坐标
                    destination = pyautogui.locateCenterOnScreen(img2,confidence=0.9)    #目标图片图片
                    print(destination)
                    if location is not None:
                        pyautogui.dragTo(destination.x,destination.y, button='left',duration=0.5)   #拖拽到目标位置
                        print('拖拽',img+"到"+img2)
                    time.sleep(1)
            i+=1


if __name__ == '__main__':
    file = 'cmd.xls'
    #打开文件
    wb = xlrd.open_workbook(filename=file)
    #通过索引获取表格sheet页
    sheet1 = wb.sheet_by_index(0)

    mainWork(sheet1)

打开网页点击目标

跟平时调用的 selenium 不同,尝试了下 pyppeteer 需求: 打开网页实现自动点击

展开代码
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import asyncio, time
from pyppeteer import launch
from win10toast import ToastNotifier


async def main(mod,webpage):
    browser = await launch(headless=mod, dumpio=True, autoClose=False,
                           args=['--no-sandbox', '--window-size=1920,1080', '--disable-infobars'])   # 进入有头模式
    page_list = await browser.pages()
    #page = await browser.newPage()           # 打开新的标签页
    page = page_list[-1]

    await page.setViewport({'width': 1920, 'height': 1080})      # 页面大小一致
    await page.goto(webpage) # 访问主页

    # evaluate()是执行js的方法,js逆向时如果需要在浏览器环境下执行js代码的话可以利用这个方法
    # js为设置webdriver的值,防止网站检测
    await page.evaluate('''() =>{ Object.defineProperties(navigator,{ webdriver:{ get: () => false } }) }''')
    # await page.screenshot({'path': './1.jpg'})   # 截图保存路径

    #page_text = await page.content()   # 获取网页源码
    #print(page_text)
    #time.sleep(1)

    # 输入要查询的关键字,type第一个参数是元素的selector,第二个是要输入的关键字
    #await page.type('#kw', 'pyppeteer')
    # 点击提交按钮 click通过selector点击指定的元素
##    await page.click('#notify-content > form > div:nth-child(4) > div > input.btn.btn-success',
##                  options={'button': 'left', #left, right, of middle, defaults to left
##                           'clickCount': 1,   # 1 or 2
##                           'delay': 300,     # 毫秒
##                           })
    #等待元素出现
    #WR = await page.waitForSelector('#notify-content > form > div:nth-child(4) > div > input.btn.btn-success')


    while True:
        try:

            await page.click('#notify-content > form > div:nth-child(4) > div > input.btn.btn-success')
            print("have a page elem")
            print("click complete,waiting for next time")
        except:
            print("waiting")
            await asyncio.sleep(60)
            await page.reload()

    #await browser.close()
    #toaster = ToastNotifier()
    #toaster.show_toast("Tip",'Complete Click github!!!', threaded=False, icon_path=None, duration=100)
mod = False
webpage = 'https://github.com/'
asyncio.get_event_loop().run_until_complete(main(mod,webpage)) #调用
1
2
python D:\pdemo\peteer\clickgithub.py
quit()

读取文本并运行保存

os.popen 可以直接 cmd 运行文本命令,尝试着用 csv 传递域名进行 ping 并保存结果

展开代码
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import os
import time
import re
import pandas as pd
import numpy as np


#读取csv文件转化为列表
def read_info(path):
    df = pd.read_csv(path)
    #ar = np.array(df)
    #lis = ar.tolist()
    lis= df.values.tolist()
    text = ["".join(l) for l in lis ]
    #print(text)
    return text

#取str符号"."中间段得字符座位文件名称保存
def find_filename(cmd,i):
    start = i.find(".",0) + 1
    end = i.find(".",start)
    name = cmd + i[start:end]
    return name

#正则查找字符串作为文件名称保存
def re_filename(cmd,i):
    pattern = re.compile(r'(?<=\.)(.*)(?=\.)')
    name = cmd + pattern.findall(i)
    return name

#保存文件名称
def save_txt(info,name):
    with open('{}.txt'.format(name),'w+')as f:
        f.write(info)
        f.close()


if __name__ == '__main__':


    weblis = ["outlook.office365.com",
              "teams.microsoft.com"]
    web = ["outlook.office365.com"]

    path = '1.csv'
    text = read_info(path)
    cmd = 'ping '

    for i in text:
        p = os.popen(cmd + i)
        print(p.read())
        name = find_filename(cmd,i)
        print(name)
        save_txt(p.read(),name)

'''
>>> help(a[0].index)
Help on built-in function index:

index(...) method of builtins.str instance
    S.index(sub[, start[, end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Raises ValueError when the substring is not found.
    '''

模拟 QQ 截图模块

流程: 根据鼠标的两个点坐标进行获取图片并保存

展开代码
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import cv2
import time,PIL,os
from PIL import ImageGrab
import numpy as np


#截图
def cut():
    global img
    scrren_cut()
    img = cv2.imread('screen.jpg')
    cv2.namedWindow('image')
    cv2.setMouseCallback('image', on_mouse)
    cv2.imshow('image', img)
    cv2.waitKey(0)
    os.remove('screen.jpg')

def scrren_cut():
    beg = time.time()
    debug = False
    # img = ImageGrab.grab(bbox=(250, 161, 1141, 610))
    image = ImageGrab.grab()
    image.save("screen.jpg")
    # PIL image to OpenCV image

def on_mouse(event, x, y, flags, param):
    global img, point1, point2
    img2 = img.copy()
    if event == cv2.EVENT_LBUTTONDOWN:         #左键点击
        point1 = (x,y)
        cv2.circle(img2, point1, 10, (0,255,0), 5)
        cv2.imshow('image', img2)
    elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):               #按住左键拖曳
        cv2.rectangle(img2, point1, (x,y), (255,0,0), 5)
        cv2.imshow('image', img2)
    elif event == cv2.EVENT_LBUTTONUP:         #左键释放
        point2 = (x,y)
        cv2.rectangle(img2, point1, point2, (0,0,255), 5)
        cv2.imshow('image', img2)
        min_x = min(point1[0],point2[0])
        min_y = min(point1[1],point2[1])
        width = abs(point1[0] - point2[0])
        height = abs(point1[1] -point2[1])
        cut_img = img[min_y:min_y+height, min_x:min_x+width]
        cv2.imwrite('cut.jpg', cut_img)

if __name__ == 'main' :
    cut()

遍历解压文件夹

流程: 遍历文件夹并解压文件

展开代码
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import os
import time
import shutil

'''
import rarfile
import zipfile
import tarfile
import gzip


def un_rar(file_name):
    """unrar zip file"""
    rar = rarfile.RarFile(file_name)
    if os.path.isdir(file_name + "_files"):
        pass
    else:
        os.mkdir(file_name + "_files")
    if os.chdir(file_name + "_files"):
        rar.extractall()
    rar.close()

def un_zip(file_name):
    """unzip zip file"""
    zip_file = zipfile.ZipFile(file_name)
    if os.path.isdir(file_name + "_files"):
        pass
    else:
        os.mkdir(file_name + "_files")
    for names in zip_file.namelist():
        zip_file.extract(names,file_name + "_files/")
    zip_file.close()

def un_tar(file_name):

    tar = tarfile.open(file_name)
    names = tar.getnames()
    if os.path.isdir(file_name + "_files"):
        pass
    else:
        os.mkdir(file_name + "_files")
    #因为解压后是很多文件,预先建立同名目录
    for name in names:
        tar.extract(name, file_name + "_files/")
    tar.close()

def un_gz(file_name):
    """ungz zip file"""
    f_name = file_name.replace(".gz", "")
    #获取文件的名称,去掉
    g_file = gzip.GzipFile(file_name)
    #创建gzip对象
    open(f_name, "w+").write(g_file.read())
    #gzip对象用read()打开后,写入open()建立的文件里。
    g_file.close()
    #关闭gzip对象

'''

def diyun_zip(file_name,root):
    if os.path.splitext(file_name)[1] == ".zip":
        shutil.unpack_archive(root+'\\'+file_name)

path = ''
file_list = os.listdir(path)
release_path = ''
os.chdir(release_path)

for root, dirs, files in os.walk(path):
    #print(files)
    for i in files:
        ##print(i)
        diy_un_zip(i,root)

HEIC 转 JPG

图片转换

展开代码
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
import os
import pillow_heif
from PIL import Image

def convert_heic_to_jpg(heic_path, jpg_path):
    """将 HEIC 格式的图像转换为 JPEG 格式并保存。"""
    try:
        # 读取 HEIC 文件
        heif_file = pillow_heif.read_heif(heic_path)
        # 创建 PIL 图像对象
        image = Image.frombytes(mode=heif_file.mode, size=heif_file.size, data=heif_file.data)

        # 检查图像模式并转换为 RGB
        if image.mode == 'RGBA':
            image = image.convert('RGB')

        # 保存为 JPEG 格式
        image.save(jpg_path, "JPEG")
        print(f"Converted: {heic_path} to {jpg_path}")
    except Exception as e:
        print(f"Error processing {heic_path}: {e}")

def recyle_convert(org_path, dst_path):
    """递归处理目录中的 HEIC 文件,将其转换为 JPEG 格式。"""
    # 确保目标路径存在
    if not os.path.exists(dst_path):
        os.makedirs(dst_path)

    # 遍历目录中的文件
    for root, _, files in os.walk(org_path):
        for file in files:
            if file.lower().endswith('.heic'):
                heic_file_path = os.path.join(root, file)
                jpg_file_path = os.path.join(dst_path, f"{os.path.splitext(file)[0]}.jpg")
                convert_heic_to_jpg(heic_file_path, jpg_file_path)

def main():
    # 源路径和目标路径
    org_path = ''
    dst_path = ''

    # 开始转换
    recyle_convert(org_path, dst_path)

if __name__ == '__main__':
    main()

区分格式

展开代码
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import shutil


# 循环读取HEIC格式照片,写入JPG
def recyle_convert(org_path, dst_path):
    # 判断是不是目录
    if os.path.isdir(org_path):
        file_list = os.listdir(org_path)
        print(file_list)
        for idx, file in enumerate(file_list):
            sub_path = os.path.join(org_path, file)
            recyle_convert(sub_path, dst_path)
    # 判断是不是文件
    elif os.path.isfile(org_path):

        # 判断照片格式
        if org_path.lower().endswith('.jpg') or org_path.lower().endswith('.mov'):

            # 读取图片
            path, filename = os.path.split(org_path)
            name, ext = os.path.splitext(filename)
            file_path = os.path.join(dst_path, '%s.jpg' % name)
            print(file_path)
            shutil.move(org_path, dst_path)


    else:
        print(org_path + 'is error format!')
    pass


# 主函数入口
def main():
    # dst path
    dst_path = ''
    #dst_path = os.getcwd()
    if os.path.exists(dst_path) is False:
        os.makedirs(dst_path)
        pass
    # org path
    org_path = ''
    # convert
    recyle_convert(org_path, dst_path)
    pass

if __name__ == '__main__':
    main()
    pass

PPTX 转 1920x1080JPG

流程:

  • 判断源文件格式,如果是 ppt,转换为 jpg 再调整格式
  • 如果是 png,转换为 jpg 再调整格式
  • 如果是 jpg,直接调整格式
展开代码
  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
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
# -*- codeing = utf-8 -*-
# @Time : 2023
# @Author : asta
# @File : trans v2.py
# @software : python 3.6.5 idle

import matplotlib.pyplot as plt
from PIL import Image
import comtypes.client
import os
import win32
import glob

#逻辑
#判断源文件格式,如果是ppt,转换为jpg再调整格式
#如果是png,转换为jpg再调整格式
#如果是jpg,直接调整格式

#png转为jpg
def pngtojpg(name):
    #如果是png,转换为jpg再调整格式
    img = Image.open(name)
    if img.mode == "RGBA":
        img = img.convert('RGB')
        print(name)
        imgname = os.path.splitext(name)[0]+ ".jpg"
        print(imgname)
        img.save(imgname)


#ppt转为jgp
def ppttojpg(openpath):

    #fileNames = glob.glob(openpath + r'\*')
##    for fileName in fileNames:     #将pa 文件夹中的文件删除。
##        os.remove( fileName)
##    powerpoint = comtypes.client.CreateObject("kwpp.Application") #使用wps的接口
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    #powerpoint.Visible = 0
    ppt = powerpoint.Presentations.Open(openpath,WithWindow=0)
    # 另存为
    pa = ''
    ppt.SaveAs(pa + '.jpg', 17)
    # 退出
    ppt.Close()
    powerpoint.Quit()


def adjust_image(file_in, width, height, file_out):

    image = Image.open(file_in)
    #resized_image = image.resize((width, height), Image.ANTIALIAS)
    resized_image = image.resize((width, height), Image.Resampling.LANCZOS)
    resized_image.save(file_out)


if __name__ == '__main__':


    width = 1920 #调整的分辨率大小
    height = 1080
    n = 0

    #设定路径
    #源文件目录
    my_dir = ''
    Files = os.listdir(my_dir)
    print(os.getcwd())

    #遍历路径下的文件
    for k in range(len(Files)):

        #将文件名
        #Files[k]=os.path.splitext(Files[k])[1]
        print(Files[k])
        file_in = ""
        if Files[k].endswith('py'):
            continue

        elif Files[k].endswith('jpg'):

            file_in = Files[k]
        elif Files[k].endswith('png'):
            pngtojpg(Files[k])
            file_in = os.path.splitext(Files[k])[0]+ ".jpg"

        elif Files[k].endswith('pptx'):
            n = n+1
            #cur_dir = os.path.dirname(os.path.abspath(Files[k]))
            #path1 = os.path.join(os.path.abspath(my_dir + os.path.sep + ".."), Files[k])
            #print(path1)
            input_file_path = os.path.join(my_dir, Files[k])
            print(input_file_path)
            ppttojpg(input_file_path)
            file_in = "Slide{0}.JPG".format(n)


        file_out = 'resized'+ file_in
        # 调整分辨率
        adjust_image(file_in, width, height, file_out)


##    Str2=['.pptx','.png','.jpg']
##    print(set(Str2).intersection(set(Files)))
##
##    if len(list(set(Str2).intersection(set(Files))))==len(Str2):
##        print("yes")
##        #return True
##    else:
##        print("no")
##        #return False

读取 sticky note 存储并导出

需求: sticky note 有时候会出现同步问题,用户突然找不到原本的便签,需要通过%LocalAppData%\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState

  • media 便笺中图片数据保存路径
  • plum.sqlite 便笺中笔记内容的主数据库文件
  • plum.sqlite-shm plum.sqlite-wal 便笺访问主数据库缓存文件
展开代码
 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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#导入sqllite3模块
import sqlite3
import re


def write_info(info):
    with open('sqlite_res_final2.txt','a+',encoding='utf-8',errors='ignore') as f:
        f.write(info)
        f.close()


# 1.硬盘上创建连接
con = sqlite3.connect('plum.sqlite')

# 获取cursor对象
cur = con.cursor()
# 执行sql创建表
#sql = 'select text from Note'
sql = 'select * from Note'

try:
    #reg = re.compile(r"^\\id=.*?\s(.*)")

    cur.execute(sql)
    person_all = cur.fetchall()
    # print(person_all)
    # 遍历
    #person_all = [("\\id=,)]
    #p = ("\\id=)
    #p[0] = "\\id=
    #print(person_all[0][0])

##    t = person_all[0][0]
##    resub = re.sub(r'(\\id=.*?\s)',"",t)
##    print(resub)

    for p in person_all:
        resub = re.sub(r'(\\id=.*?\s)',"",p[0])
        #print(resub)
        #print(reg.findall(p[0]))
        #write_info(p[0])
        #print(p[0])


        write_info(resub)
except Exception as e:
    print(e)
    print('创建表失败')
finally:
    # 关闭游标
    cur.close()
    # 关闭连接
    con.close()

苹果手机的相片按照时间排序处理

读取 aae 格式

展开代码
 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
from PIL import Image
from PIL.ExifTags import TAGS

def get_image_date(image_path):
    try:
        with Image.open(image_path) as img:
            exif_data = img._getexif()
            if exif_data is not None:
                for tag, value in exif_data.items():
                    tag_name = TAGS.get(tag)
                    if tag_name == 'DateTimeOriginal':
                        return value
    except (IOError, AttributeError):
        pass

    return None

# 指定AAE文件路径
aae_file_path = ''

# 构建对应的照片文件路径
photo_file_path = aae_file_path.replace('.aae', '')

# 获取照片日期
photo_date = get_image_date(photo_file_path)

if photo_date is not None:
    print("照片日期:", photo_date)
else:
    print("无法获取照片日期信息。")

读取相片时间

展开代码
 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
34
35
36
37
38
39

from PIL import Image
from PIL.ExifTags import TAGS
import os


def get_image_date(image_path):
    try:
        with Image.open(image_path) as img:
            exif_data = img._getexif()
            if exif_data is not None:
                for tag, value in exif_data.items():
                    tag_name = TAGS.get(tag)
                    #print(tag_name,value)
                    if tag_name == 'DateTimeOriginal':
                        return value
    except (IOError, AttributeError):
        pass

    return None





my_dir = ''
Files = os.listdir(my_dir)
for k in range(len(Files)):
    print(Files[k])
# 指定图片路径
    image_path = os.path.join(my_dir, Files[k])

# 获取图片日期
    image_date = get_image_date(image_path)

    if image_date is not None:
        print("图片日期:", image_date)
    else:
        print("无法获取图片日期信息。")

最后更新于 05月19日 12点44分, 2026年