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

标签 python regex python-3.x shutil

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

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)

关于python - 如何改进在 Python 中移动所有不包含特定日期的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52416189/

相关文章:

javascript - 用单引号引起来时,正则表达式不起作用

Python 3 : subprocess. run ('mv' )使目标保持打开状态

python - 如何计算 Pandas 多索引的真假?

python - 父类(super class)的方法不被子类继承

python - 获取Python匹配对象中的所有未命名组

python - 使用稀疏矩阵与 sklearn 亲和性传播

Java正则表达式用特殊字符替换字符串

regex - Perl - 用于查找和替换不属于字符实体的&符号的正则表达式

Python。代码在 csv 文件中每行后留下空白行

python - ZeroMQ 和 Python 中的多个订阅过滤器