Skip to main content
 首页 » 编程设计

python之如何改进在 Python 中移动所有不包含特定日期的文件

2024年12月31日12jiqing9006

我想移动所有不是今天开始的文件,我的代码如下,我可以更快地改进它吗?

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) 

请您参考如下方法:

可以先获取今天开始的POSIX时间戳,然后使用os.path.getmtime()获取每个文件的最后修改时间的时间戳进行比较:

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) 

但是,比使用 os.listdir() 并在目录中的每个文件上调用 os.path.getmtime() 更有效的方法是使用 os.scandir()(参见 PEP-471 ),它将给定目录中所有文件条目的属性缓存在一个对象中,因此不需要对每个文件条目进行额外的系统调用:

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)