批量修改文件的修改时间(图文)
批量修改文件的修改时间有多种方法,以下是不同操作系统和场景下的详细操作:
选择合适的批量修改方法取决于您的具体需求:
1. Windows 系统
使用 PowerShell:
powershell
# 修改指定目录下所有 .txt 文件的修改时间 Get-ChildItem "C:\path\to\folder\*.txt" | ForEach-Object { $_.LastWriteTime = "2023-12-01 15:30:00" } # 修改指定目录及子目录下所有文件 Get-ChildItem "C:\path\to\folder" -Recurse | ForEach-Object { $_.LastWriteTime = "2023-12-01 15:30:00" } # 根据文件类型设置不同时间 Get-ChildItem "C:\path\to\folder" -Recurse | ForEach-Object { switch ($_.Extension) { ".txt" { $_.LastWriteTime = "2023-12-01 15:30:00" } ".pdf" { $_.LastWriteTime = "2023-11-30 10:00:00" } ".jpg" { $_.LastWriteTime = "2023-11-25 14:00:00" } default { $_.LastWriteTime = "2023-12-01 09:00:00" } } }使用批处理脚本 (.bat):
batch
@echo off REM 修改当前目录下所有 .txt 文件时间 for %%f in (*.txt) do ( copy /b "%%f" +,, >nul echo 已更新: %%f ) REM 修改指定目录下所有文件时间 for /R "C:\path\to\folder" %%f in (*) do ( copy /b "%%f" +,, >nul echo 已更新: %%f )2. Mac 和 Linux 系统
使用 find 和 touch 命令:
bash
# 修改目录下所有 .txt 文件 find /path/to/folder -name "*.txt" -exec touch -m -d "2023-12-01 15:30:00" {} \; # 修改目录及子目录下所有文件 find /path/to/folder -type f -exec touch -m -d "2023-12-01 15:30:00" {} \; # 修改特定时间范围内修改过的文件 find /path/to/folder -type f -mtime -7 -exec touch -m -d "2023-12-01 15:30:00" {} \; # 根据文件类型批量修改 find /path/to/folder -name "*.pdf" -exec touch -m -d "2023-11-30 10:00:00" {} \; find /path/to/folder -name "*.jpg" -exec touch -m -d "2023-11-25 14:00:00" {} \;使用 shell 脚本:
bash
#!/bin/bash # 设置变量 TARGET_DIR="/path/to/folder" NEW_TIME="2023-12-01 15:30:00" # 修改所有文件的修改时间 find "$TARGET_DIR" -type f -exec touch -m -d "$NEW_TIME" {} \; # 或者使用循环方式 for file in $(find "$TARGET_DIR" -type f); do touch -m -d "$NEW_TIME" "$file" echo "已更新: $file" done3. Python 脚本方案
基础批量修改脚本:
python
import os import glob from datetime import datetime def batch_change_modification_time(pattern, new_datetime_str): """ 批量修改匹配模式的文件修改时间 :param pattern: 文件匹配模式,如 "/path/to/folder/*.txt" :param new_datetime_str: 新的时间字符串 """ # 解析时间 new_datetime = datetime.strptime(new_datetime_str, "%Y-%m-%d %H:%M:%S") timestamp = new_datetime.timestamp() # 获取所有匹配的文件 files = glob.glob(pattern, recursive=True) for file_path in files: if os.path.isfile(file_path): # 确保是文件而不是目录 try: # 保持访问时间不变,只修改修改时间 stat = os.stat(file_path) os.utime(file_path, (stat.st_atime, timestamp)) print(f"✓ 已更新: {file_path}") except Exception as e: print(f"✗ 更新失败 {file_path}: {e}") # 使用示例 batch_change_modification_time("/path/to/folder/*.txt", "2023-12-01 15:30:00") batch_change_modification_time("/path/to/folder/**/*.pdf", "2023-11-30 10:00:00") # 递归搜索高级批量修改脚本:
python
import os import fnmatch from datetime import datetime from pathlib import Path class BatchFileTimeModifier: def __init__(self, root_directory): self.root_directory = Path(root_directory) def modify_by_extension(self, extension_map): """ 根据文件扩展名设置不同的修改时间 :param extension_map: 字典,格式 {".ext": "YYYY-MM-DD HH:MM:SS"} """ for ext, time_str in extension_map.items(): self._modify_files_by_extension(ext, time_str) def _modify_files_by_extension(self, extension, time_str): """修改特定扩展名的文件""" new_datetime = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S") timestamp = new_datetime.timestamp() # 递归查找所有匹配的文件 pattern = f"*{extension}" for file_path in self.root_directory.rglob(pattern): if file_path.is_file(): try: stat = file_path.stat() os.utime(str(file_path), (stat.st_atime, timestamp)) print(f"✓ [{time_str}] {file_path}") except Exception as e: print(f"✗ 失败 {file_path}: {e}") def modify_by_size_range(self, min_size, max_size, time_str): """根据文件大小范围修改时间""" new_datetime = datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S") timestamp = new_datetime.timestamp() for file_path in self.root_directory.rglob("*"): if file_path.is_file(): file_size = file_path.stat().st_size if min_size <= file_size <= max_size: try: stat = file_path.stat() os.utime(str(file_path), (stat.st_atime, timestamp)) print(f"✓ [{time_str}] {file_path} ({file_size} bytes)") except Exception as e: print(f"✗ 失败 {file_path}: {e}") # 使用示例 modifier = BatchFileTimeModifier("/path/to/folder") # 根据扩展名设置不同时间 extension_time_map = { ".txt": "2023-12-01 15:30:00", ".pdf": "2023-11-30 10:00:00", ".jpg": "2023-11-25 14:00:00", ".docx": "2023-11-28 09:30:00" } modifier.modify_by_extension(extension_time_map) # 根据文件大小修改时间 (小于1MB的文件) modifier.modify_by_size_range(0, 1024*1024, "2023-12-01 12:00:00")4. 使用第三方工具
ExifTool (跨平台):
bash
# 批量修改图片文件的修改时间 exiftool -FileModifyDate="2023:12:01 15:30:00" /path/to/folder/*.jpg # 递归修改所有子目录中的文件 exiftool -r -FileModifyDate="2023:12:01 15:30:00" /path/to/folder/ # 根据文件类型设置不同时间 exiftool -ext jpg -FileModifyDate="2023:11:25 14:00:00" /path/to/folder/ exiftool -ext pdf -FileModifyDate="2023:11:30 10:00:00" /path/to/folder/5. 高级脚本功能
带进度条和日志的批量修改:
python
import os import glob from datetime import datetime from tqdm import tqdm import logging # 设置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler('file_time_modify.log'), logging.StreamHandler() ] ) def advanced_batch_modify(pattern, new_time_str, create_log=True): """ 带进度条和日志的高级批量修改 """ try: new_datetime = datetime.strptime(new_time_str, "%Y-%m-%d %H:%M:%S") timestamp = new_datetime.timestamp() # 获取所有文件 files = glob.glob(pattern, recursive=True) files = [f for f in files if os.path.isfile(f)] if not files: logging.warning(f"未找到匹配的文件: {pattern}") return logging.info(f"开始处理 {len(files)} 个文件") # 使用进度条处理文件 success_count = 0 error_count = 0 for file_path in tqdm(files, desc="处理文件"): try: stat = os.stat(file_path) os.utime(file_path, (stat.st_atime, timestamp)) success_count += 1 if create_log: logging.info(f"成功更新: {file_path}") except Exception as e: error_count += 1 logging.error(f"更新失败 {file_path}: {e}") logging.info(f"处理完成: 成功 {success_count}, 失败 {error_count}") except Exception as e: logging.error(f"批量处理过程中发生错误: {e}") # 使用示例 advanced_batch_modify("/path/to/folder/**/*", "2023-12-01 15:30:00")6. 注意事项和最佳实践
安全建议:
bash
# 在执行批量操作前先预览将要修改的文件 find /path/to/folder -name "*.txt" -print # 或者使用 Python 脚本的 dry-run 模式 def batch_modify_dry_run(pattern, new_time_str): files = glob.glob(pattern, recursive=True) files = [f for f in files if os.path.isfile(f)] print(f"将要修改 {len(files)} 个文件的时间:") for file_path in files: print(f" {file_path}") confirm = input("确认执行修改? (y/N): ") if confirm.lower() == 'y': # 执行实际修改 batch_change_modification_time(pattern, new_time_str)权限处理:
bash
# 如果遇到权限问题,可能需要使用 sudo (Linux/Mac) sudo find /path/to/folder -name "*.txt" -exec touch -m -d "2023-12-01 15:30:00" {} \;- 简单任务:使用系统命令(PowerShell/touch)
- 复杂逻辑:使用 Python 脚本
- 专业用途:使用 ExifTool 等专业工具
- 大量文件:考虑性能优化和错误处理

更新时间:2025-12-14 17:24:44
上一篇:怎么修改文件的修改日期(图文)
下一篇:上传的文件怎么修改内容(图文)
