Python:如何克服文件路径不正确的无效参数



我正试图编写一个Python脚本,每次按下鼠标左键时都会捕获屏幕截图。我使用本指南作为参考:https://pytutorial.com/python-capture-screenshot-mouse-clicked

我的问题来自文件路径。我想要将屏幕截图保存在";屏幕截图";文件夹,但我得到了错误,"OSError: [Errno 22] Invalid argument: 'C:/Users/tjdob/codebase/Screenshoots//26-10-2022_22:12:52.jpg'"

我的基本目录是C:Userstjdobcodebase

这是我试图运行的代码:

from pymouse import PyMouseEvent
import pyautogui
import os

class ScreenshotsTaker(PyMouseEvent):
def __init__(self, path):
self.path = path # path to save Screenshot
PyMouseEvent.__init__(self)
def click(self, x, y, button, press):
# if button number 1
if button == 1:
# if button number 1 is pressed (clicked)
if press:
# Take ScreenShot
myScreenshot = pyautogui.screenshot()
# Save ScreenShot file
now = datetime.now()
# Date Time Now
dt_string = now.strftime("%d-%m-%Y_%H:%M:%S")
# Save ScreenShot
myScreenshot.save(os.path.join(self.path,dt_string + ".jpg"))
# Output:
print("ScreenShot is taken")

C = ScreenshotsTaker(path="C:/Users/tjdob/codebase/Screenshoots//")
C.run()

我相信这是一个简单的解决方案。任何方向都将受到赞赏

我尝试过更改文件路径,并将反斜杠与正斜杠进行切换。

问题出在使用strftime():创建的文件名上

26-10-2022_22:12:52.jpg

Windows文件名中不能有:,因为文件路径中的:是驱动器号(例如C:(和路径之间的分隔符。使用:作为名为Alternative Data Streams的功能的一部分是一个例外,但这不是您在这里要做的。

因为它不是有效的文件路径,所以会得到Invalid argument错误。

您必须以不同的方式格式化文件名的时间戳部分——可能的替代格式选项有:

%H-%M-%S   ->   22-12-52
%H.%M-%S   ->   22.12.52
%H%M%S     ->   221252