How to improve moving all files not contains specific date in Python?

Viewed 31

I want to move all files not start with date of today, my code as below, can I improve it more faster?

today = datetime.datetime.today().strftime('%Y%m%d')
all_files = os.listdir(image_current_path)
for i, image_file in enumerate(all_files):
    if not image_file.startswith(today):
        image_file = os.path.join(image_current_folder, image_file) # added
        shutil.move(image_file, image_old_path)
1 Answers

You can get the POSIX timestamp of the beginning of today first, and then use os.path.getmtime() to get the timestamp of the last modification time of each file for comparison:

from datetime import datetime, date, time
import os

today = datetime.combine(date.today(), time.min).timestamp()
for image_file in os.listdir(image_current_path):
    path = os.path.join(image_current_path, image_file)
    if os.path.getmtime(path) < today:
        shutil.move(path, image_old_path)

Rather than using os.listdir() and calling os.path.getmtime() on each file in a directory, however, a much more efficient method is to use os.scandir() (see PEP-471), which caches the attributes of all file entries in a given directory in an object so no additional system call needs to be made on every file entry:

from datetime import datetime, date, time
import os

today = datetime.combine(date.today(), time.min).timestamp()
for image_file in os.scandir(image_current_path):
    if image_file.stat().st_mtime < today:
        shutil.move(os.path.join(image_current_path, image_file.name), image_old_path)
Related