【问题标题】:Get the date a file was created, create a folder with that date and move the files获取文件的创建日期,使用该日期创建文件夹并移动文件
【发布时间】:2019-11-26 17:46:04
【问题描述】:

我正在尝试自动组织包含 3000 多张照片的摄影文件夹。

我想获取文件的创建日期,创建一个该日期的新文件夹,格式为DD-MM-YYYY,然后将文件从当前文件夹移到新文件夹中。

我能够使用以下代码检索其中一个文件的创建日期

print("created: %s" % time.ctime(os.path.getctime(file)))

返回created: Fri Mar 22 17:49:36 2019

以下是该文件夹的示例。在这种情况下,创建日期与修改日期相同,但并非总是如此!

我怎样才能做到这一点?

【问题讨论】:

    标签: python python-3.x python-datetime


    【解决方案1】:

    您可以使用mtime 而不是ctime,但从您的屏幕截图中可以看出,据我所知,没有办法在 Windows 上获得“时间创建”时间。 ctime 代表更改时间,比mtime 更容易更改。 (详细解释here

    为了达到你的目标,你可以做的是从你的图像中读出 EXIF 数据。它们应该保存您拍摄图像的日期和时间。如果您不确定,如果您的图像包含 EXIF 数据,您可以使用以下脚本回退到 mtime,如果没有找到 exif 数据:

    import exifread
    import shutil
    import os
    import sys
    import datetime
    
    ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'cr2'])
    
    def allowed_file(filename):
        return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
    
    if len(sys.argv) < 1:
        print('Please provide directory as argument!')
    
    directory = sys.argv[1] # get the directory where we are looking for images
    img_files = os.listdir(directory)  # get the files of the directory
    
    for img in img_files:
        date = None
        if allowed_file(img): # check if the file is an image file
            full_path = os.path.join(directory, img)
            with open(full_path, 'rb') as image_file:
                tags = exifread.process_file(image_file, stop_tag='EXIF DateTimeOriginal')
                date_taken = str(tags.get('EXIF DateTimeOriginal'))
                try:
                    date_time_obj = datetime.datetime.strptime(date_taken, '%Y:%m:%d %H:%M:%S')
                    date = date_time_obj.date() # getting the date in YYYY-MM-DD format
                except ValueError:
                    print('Cannot find EXIF')
            if not date:
                print('Using mtime')
                mtime = os.path.getmtime(full_path)
                date_time_obj = datetime.datetime.fromtimestamp(mtime)
                date = date_time_obj.date()
            print('Image: {} - Date: {}'.format(img, date))
            new_directory = 'Sorted/{}'.format(date)
            os.makedirs(new_directory, exist_ok=True)  # make the new directory
            shutil.copyfile(full_path, os.path.join(new_directory, img))  # copy file into the new directory - it will have the format YYYY-MM-DD
    

    此脚本将从您的图像中读取 EXIF 数据,如果没有,它会回退到 mtime,创建文件夹并将图像复制到文件夹中。

    请注意,在此脚本中,我将日期格式化为 YYYY-MM-DD。您当然可以轻松更改它。只是Sorted-文件夹中的目录按升序显示,比较方便。但当然不是强制性的。

    如果您将脚本设置为sort.py,则可以使用python sort.py &lt;directory-to-sort&gt; 启动它。 (exifreadshutil 必须在此之前通过pip install 安装)

    【讨论】:

      【解决方案2】:

      您可以使用os.listdir 获取目录中的文件列表,然后通过os.path.isfile 和/或f.endswith 过滤它们以仅接受图像文件。您几乎拥有时间戳代码(您可以使用strftime 对其进行格式化),因此只需使用os.makedirs 创建任何必要的目录并使用os.replace 复制文件。

      所有相关方法都可以在osdatetime 模块的文档中找到。

      import os
      from datetime import datetime
      
      path = "."
      ext = "CR2"
      
      for f in os.listdir(path):
          fpath = os.path.join(path, f)
      
          if os.path.isfile(fpath) and fpath.endswith(ext):
              time = datetime.fromtimestamp(os.path.getctime(fpath)).strftime("%d-%m-%Y")
              os.makedirs(os.path.join(path, time), exist_ok=True)
              os.replace(fpath, os.path.join(path, time, f))
      

      如果你想接受多个扩展名并按扩展名将它们组织到子文件夹中,你可以使用:

      import os
      from datetime import datetime
      
      path = "foo"
      exts = set(["cr2", "jpg"])
      
      for f in os.listdir(path):
          fpath = os.path.join(path, f)
          ext = f.split(".")[-1].lower()
      
          if os.path.isfile(fpath) and ext in exts:
              time = datetime.fromtimestamp(os.path.getctime(fpath)).strftime("%d-%m-%Y")
              os.makedirs(os.path.join(path, time, ext), exist_ok=True)
              os.replace(fpath, os.path.join(path, time, ext, f))
      

      【讨论】:

      • 有没有办法添加另一个 if 语句,如果文件是 CR2,则添加到该文件夹​​,但如果文件是 .JPG 或 .JPEG,则在该文件夹中创建一个名为 JPEG Files 的文件夹和而是将其添加到那里?
      • 确实如此。你刚刚为我节省了几个小时的工作时间。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多