1

First of all, I'm new to programming and Python in particular, therefore I'm struggling to find a right solution.

I'm trying to search the files with specific extension recursively which have been created only in last 24 hours and either print the result to the screen, save to the file, and copy those files to directory.

Below is an example the code which does most of what I would like to achieve, except it finds all files with given extension, however, I need only files created in last 24 or less hours.

import os
import shutil

topdir = r"C:\Docs"
dstdir = r"C:\test" 

exten =  ".png"

for dname, names, files in os.walk(topdir):
    for name in files:
        if name.lower().endswith(exten):
            # Prints result of walk
            print(os.path.join(dname, name))
            #copy all files with given extension to the dst folder 
            path = os.path.realpath(os.path.join(dname, name))
            shutil.copy2(path, dstdir)      
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
Marek W.
  • 11
  • 1

1 Answers1

1
compare_date = datetime.datetime.today() - datetime.timedelta(hours = 24)

Inside nested loop, you can add these code

create_dt = os.stat(name).st_mtime
created_date = datetime.datetime.fromtimestamp(create_dt)
if created_date > compare_date:
    print name
Vineesh
  • 253
  • 2
  • 7
  • Thanks Vineesh, but I'm receiving following error when finds .pdf file "FileNotFoundError: [WinError 2] The system cannot find the file specified" – Marek W. Sep 15 '15 at 15:07
  • @MarK I suspect, the pdf file is not in current working directory. you can add full path of file in "create_dt" like create_dt = os.stat(dname+'\'+name).st_mtime. This might help you. – Vineesh Sep 16 '15 at 07:50
  • Unfortunately your suggestion didn't help, getting now - create_dt = os.stat(dname+'\'+name).st_mtime ^ SyntaxError: EOL while scanning string literal Regarding previous search, I do not search for pdf, I try to find, lets say .py files in provided dir, it finds any .py files created in last 24 hours and then try to do further search in subdirectories, finds first file other than extension provided and throws that error. – Marek W. Sep 16 '15 at 08:44