Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何改进在Python中移动所有不包含特定日期的文件?_Python_Regex_Python 3.x_Shutil - Fatal编程技术网

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

如何改进在Python中移动所有不包含特定日期的文件?,python,regex,python-3.x,shutil,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(im

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

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)

您的第一种方法需要添加
image\u file=os.path.join(image\u current\u folder,image\u file)
在shutil.move之前,我还修改了我的问题。哎呀,我忘了使用
image\u file.name
<代码>图像_文件是一个
DirEntry
对象。我已经相应地更新了我的答案。您的解决方案2移动了所有文件,包括今天:(
1537402210.8215256<1537411062.2788
对于文件
201809200005\u box\u img0\u A.png
我明白了。我忘了您应该将时间缩短到一天的开始。请现在再试一次。
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)