2017/5/19

[python]整理圖片程式

常常拍了很多照片、搜集很多圖片之後,
由於拍照來源不同或圖片來源不同而造成檔案整理時的困擾,
因此萌發寫出這個程式的念頭,讓相片利用內定拍攝日期自動排列。

以下為程式碼


##Picture_Sort
#20160516
import os
import shutil

#Get all the filenames of the current directory
filenames = os.listdir(".")
#Identify the picture
def is_image(filenames):
 return os.path.splitext(filenames)[-1] in [".png",".jpg"]
#Get the filenames of all pictures
images = filter(is_image, filenames)


from datetime import datetime

#Get time
def get_time(filenames):
 timestamp = os.path.getmtime(filenames)
 return datetime.fromtimestamp(timestamp)

#Sort by time
filenames.sort(key=get_time)

last_modified = None
for filename in filenames:
 modified = get_time(filename)

 #number
 if last_modified and last_modified.date() == modified.date():
  num += 1
 else:
  num = 1

 #name the file according to time and number
 targetname = "{}.{}.jpg".format(modified.strftime("%Y-%m-%d"), num)

 #rename
 shutil.move(filename, targetname)

 last_modified = modified