Iwan
Iwan

Reputation: 319

Selecting files by date and containing text, Python

I'm trying to select specific files in Windows within a specified timeframe, and if it includes specific text.

for folderName, subfolders, filenames in os.walk(r'C:\User\Documents\Reports'):

    for file in filenames:
            if os.path.getmtime(file) < datetime.timedelta(days=31) AND if 'Summary' in file or 'Summaries' in file :
                    try: shutil.copy(os.path.join(folderName, file), r'C:\User\Documents\File_Selections')
                    except: 
                            print(folderName, file)

So I'm looking through the Reports folder for each file that was last modified in the last month, AND if it's name includes 'summary' or 'summaries'. I then want to copy each file to a specific folder and print out the results.

My main problem is how does the date comparison work, so that only files modified in the last month are selected? Also I was unsure if the AND operator is being used correctly within the 'if' statement.

Upvotes: 0

Views: 1295

Answers (1)

user2556381
user2556381

Reputation:

You don't need the if keyword after the and keyword. The and is correct. You are selecting all files in the directory that are not older than a month AND they contain either 'summary' or 'summaries'

The line
if os.path.getmtime(file) < datetime.timedelta(days=31) and 'Summary' in file or 'Summaries' in file:

won't be working, since os.path.getmtime() returns a float.

What you need to do is to use total_seconds() after the call to datetime.timedelta. For example,

if os.path.getmtime(file) < datetime.timedelta(days=31).total_seconds()

total_seconds() will return the datetime.timedelta value as a float

Upvotes: 2

Related Questions