Python 通过文件夹进行迭代并查找特定文件的时间戳时出现问题

Python 通过文件夹进行迭代并查找特定文件的时间戳时出现问题,python,datetime,script,os.path,Python,Datetime,Script,Os.path,我在Python中编写了一个函数,它遍历根文件夹,根文件夹中包含不同的文件夹 这些文件夹包含许多不同的文件,但我特别只在过去24小时内创建的文件夹中查找PNG文件 我写了这段代码,但不幸的是我得到了一个错误 for root, dirs, files in os.walk(rootFolder): # if(datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y") == "2021&q

我在Python中编写了一个函数,它遍历根文件夹,根文件夹中包含不同的文件夹

这些文件夹包含许多不同的文件,但我特别只在过去24小时内创建的文件夹中查找PNG文件

我写了这段代码,但不幸的是我得到了一个错误

    for root, dirs, files in os.walk(rootFolder):

   # if(datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y") == "2021"):
        for file in files:  

            if file.endswith(".png"):
                time = datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y")

                print(datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d"))
当我试图打电话时:

print(datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d"))
我得到“FileNotFoundError:[WinError 2]找不到文件:'001-001-001.png'

我不明白这个“未找到”部分,当它在错误消息中向我返回名称时

如果我改为在函数中写入root,我将得到一个结果并返回时间戳,但这些不是我需要的

print(datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d"))
我正在考虑这样做:

   for root, dirs, files in os.walk(rootFolder):

   # if(datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y") == "2021"):
        for file in files:  

            if file.endswith(".png") and datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d") == datetime.now().strftime("%Y:%m:%d"):
                time = datetime.fromtimestamp(os.path.getctime(root)).strftime("%Y")

                print(datetime.fromtimestamp(os.path.getmtime(file)).strftime("%Y:%m:%d"))
在这里,我将比较png文件的时间戳和当前时间,并检查它们是否早于24小时/天..但不幸的是,由于代码无法将“file”作为getmtime()函数中的输入,我得到了一个错误


我希望有人能帮助我。

脚本是否使用预期的目录

您可以通过以下方式检查目录:

print(“当前目录:”,os.getcwd())
打印(“根:”,根)
打印(“当前文件:”,文件)
如果从PNG文件夹运行初始脚本,它应该可以工作

或者使用文件的完整路径,例如:

timestamp=os.path.getmtime(os.path.join(根,文件))
打印(datetime.fromtimestamp(timestamp).strftime(“%Y:%m:%d”))