[Python] 文件按照时间分类脚本
import os
import shutil
import datetime
def classify_files_by_date(directory):
if not os.path.exists(directory):
print(f"Error: Directory {directory} does not exist.")
return
for filename in os.listdir(directory):
file_path = os.path.join(directory, filename)
if os.path.isfile(file_path): # 确保是文件
modified_time = datetime.datetime.fromtimestamp(os.path.getmtime(file_path))
year = str(modified_time.year)
month = str(modified_time.month)
target_dir = os.path.join(directory, year, month)
os.makedirs(target_dir, exist_ok=True) # 创建目标目录
target_path = os.path.join(target_dir, filename)
try:
shutil.move(file_path, target_path) # 移动文件
print(f"Moved: {file_path} -> {target_path}")
except Exception as e:
print(f"Error moving {file_path} to {target_path}: {e}")
if __name__ == "__main__":
base_directory = "/vol3/1000/Data/Photos/Camera/" # 修改为你的目标路径
classify_files_by_date(base_directory)
使用方法, python pyfile.py
[Python] 文件按照时间分类脚本
https://blog.onanii0721.website//archives/wen-jian-an-zhao-shi-jian-fen-lei-de-pythonjiao-ben