PyAutoGUI截图存图命名错误,Python版本差异是否有影响?
问题:TXT文件截图后命名错乱(如1.txt存为3.png)
我编写了一段Python脚本,用于为目录中的每个.txt文件截图并保存为同名.png文件,但出现命名错误(如1.txt被错误保存为3.png)。此外首次打开文件时存在过度缩放问题,但当前优先解决命名错误问题。
原脚本代码
import os import pyautogui import subprocess def process_text_file(filename): subprocess.call(["open", "-a", "TextEdit", filename]) pyautogui.sleep(1) for i in range(10): pyautogui.hotkey("command", "-") pyautogui.hotkey("ctrl", "command", "f") for i in range(4): pyautogui.keyDown('shift') pyautogui.keyDown('command') pyautogui.press('.') pyautogui.keyUp('shift') pyautogui.keyUp('command') pyautogui.hotkey("command", "up") pyautogui.sleep(1) screenshot = pyautogui.screenshot() pyautogui.sleep(1) screenshot_filename = os.path.splitext(filename)[0] + ".png" screenshot.save(screenshot_filename) pyautogui.hotkey("command", "w") filename = "00.jpg.txt" for filename in os.listdir(os.getcwd()): if filename.endswith(".txt"): process_text_file(filename)
(注:原脚本循环部分缺少缩进,已补充)
排查与解决过程
- 尝试过增加
pyautogui.sleep(1)、通过终端循环执行脚本、使用natsorted对文件列表排序等方法,均未解决问题 - 发现版本差异:使用Python 3.9.12的电脑无此问题,而我常用的Python 3.9.6版本(Mac Ventura,M1)的电脑存在该问题
- 统一依赖、操作系统及处理器后,调整代码执行顺序:将
screenshot = pyautogui.screenshot()代码移至保存文件并关闭程序之后,问题得以解决
调整后的核心代码片段:
pyautogui.sleep(1) # 先生成保存文件名并关闭当前文件窗口 screenshot_filename = os.path.splitext(filename)[0] + ".png" pyautogui.hotkey("command", "w") # 执行截图并保存 screenshot = pyautogui.screenshot() pyautogui.sleep(1) screenshot.save(screenshot_filename)
内容的提问来源于stack exchange,提问作者pierogie
相关产品推荐
相关产品推荐

