获取文件的创建日期,使用该日期创建文件夹并移动文件
Get the date a file was created, create a folder with that date and move the files
我正在尝试自动整理包含 3000 多张照片的摄影文件夹。
我想获取文件的创建日期,创建一个日期格式为 DD-MM-YYYY
的新文件夹,然后将文件从当前文件夹移动到新文件夹中。
我能够使用以下代码检索其中一个文件的创建日期
print("created: %s" % time.ctime(os.path.getctime(file)))
其中 returns created: Fri Mar 22 17:49:36 2019
.
下面是文件夹的示例。在这种情况下,创建日期与修改日期相同,但情况并非总是如此!
我怎样才能做到这一点?
您可以使用 os.listdir
获取目录中的文件列表,然后通过 os.path.isfile
and/or f.endswith
过滤它们以仅接受图像文件。您几乎拥有时间戳代码(您可以使用 strftime
对其进行格式化),因此只需使用 os.makedirs
创建任何必要的目录并使用 os.replace
.[=21 复制文件=]
所有相关方法都可以在 os
and datetime
模块的文档中找到。
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))
您可以使用 mtime
而不是 ctime
,但从您的屏幕截图来看,据我所知,无法获得 'time created' 时间 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 数据,如果有 none,它会回退到 mtime
,创建文件夹并将图像复制到文件夹中。
请注意,在此脚本中,我将日期格式设置为 YYYY-MM-DD。您当然可以轻松更改它。只是,Sorted
-文件夹中的目录是按升序显示的,这样很方便。但当然不是强制性的。
如果您将脚本安全设置为 sort.py
,则可以使用 python sort.py <directory-to-sort>
启动它。 (exifread
和 shutil
必须先通过 pip install
安装)
我正在尝试自动整理包含 3000 多张照片的摄影文件夹。
我想获取文件的创建日期,创建一个日期格式为 DD-MM-YYYY
的新文件夹,然后将文件从当前文件夹移动到新文件夹中。
我能够使用以下代码检索其中一个文件的创建日期
print("created: %s" % time.ctime(os.path.getctime(file)))
其中 returns created: Fri Mar 22 17:49:36 2019
.
下面是文件夹的示例。在这种情况下,创建日期与修改日期相同,但情况并非总是如此!
我怎样才能做到这一点?
您可以使用 os.listdir
获取目录中的文件列表,然后通过 os.path.isfile
and/or f.endswith
过滤它们以仅接受图像文件。您几乎拥有时间戳代码(您可以使用 strftime
对其进行格式化),因此只需使用 os.makedirs
创建任何必要的目录并使用 os.replace
.[=21 复制文件=]
所有相关方法都可以在 os
and datetime
模块的文档中找到。
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))
您可以使用 mtime
而不是 ctime
,但从您的屏幕截图来看,据我所知,无法获得 'time created' 时间 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 数据,如果有 none,它会回退到 mtime
,创建文件夹并将图像复制到文件夹中。
请注意,在此脚本中,我将日期格式设置为 YYYY-MM-DD。您当然可以轻松更改它。只是,Sorted
-文件夹中的目录是按升序显示的,这样很方便。但当然不是强制性的。
如果您将脚本安全设置为 sort.py
,则可以使用 python sort.py <directory-to-sort>
启动它。 (exifread
和 shutil
必须先通过 pip install
安装)