You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将文件复制到带当前时间戳的目录中?

问题描述

我创建了一个带有当前时间戳(12:32:57 PM)的目录,想要将文件复制到该时间戳目录中,请问该如何操作?我尝试运行以下代码:

import os  
import shutil 

cmd_mkdir = 'mkdir /home/mubashir/catkin_ws/src/germany1_trush/ros_bag_saved/"$(date +%r)"'
os.system(cmd_mkdir)

origin_past=f'/home/mubashir/catkin_ws/src/germany1_trush/rosbag/1.bag'
target_past=f'/home/mubashir/catkin_ws/src/germany1_trush/ros_bag_saved/$(date +%r)/1.bag'
shutil.copy(origin_past,target_past)
问题分析

你的代码存在几个核心问题:

  • 时间戳不一致:两次调用date +%r可能生成不同时间(哪怕间隔1秒),导致实际创建的目录和复制目标路径不匹配。
  • 路径解析错误:Python的f-string不会解析shell命令$(date +%r),target_past里的这部分会被当作字面量,直接导致路径无效。
  • 引号处理错误:代码里的"是HTML转义的双引号,实际执行时无法正确包裹带空格的时间戳目录名,可能导致目录创建失败或被拆分成多个目录。
解决方法

方法一:Python原生实现(推荐)

用Python内置模块生成统一时间戳,直接创建目录并复制文件,完全不依赖shell命令,更可靠:

import os
import shutil
from datetime import datetime

# 生成和`date +%r`格式一致的时间戳(12小时制带AM/PM)
timestamp = datetime.now().strftime("%I:%M:%S %p")
# 定义目标目录路径
target_dir = f'/home/mubashir/catkin_ws/src/germany1_trush/ros_bag_saved/{timestamp}'
# 创建目录(exist_ok=True避免目录已存在时报错)
os.makedirs(target_dir, exist_ok=True)

# 执行文件复制
origin_path = '/home/mubashir/catkin_ws/src/germany1_trush/rosbag/1.bag'
target_path = os.path.join(target_dir, '1.bag')
shutil.copy(origin_path, target_path)

方法二:shell命令实现(仅作参考)

如果一定要通过shell创建目录,需要先捕获生成的目录名,再用于复制(仍存在极端情况下时间戳不一致的风险):

import os
import shutil
import subprocess

# 执行mkdir命令并返回创建的目录路径
cmd = 'mkdir -p /home/mubashir/catkin_ws/src/germany1_trush/ros_bag_saved/"$(date +%r)" && echo /home/mubashir/catkin_ws/src/germany1_trush/ros_bag_saved/"$(date +%r)"'
result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
target_dir = result.stdout.strip()

# 复制文件
origin_path = '/home/mubashir/catkin_ws/src/germany1_trush/rosbag/1.bag'
target_path = os.path.join(target_dir, '1.bag')
shutil.copy(origin_path, target_path)

内容的提问来源于stack exchange,提问作者Mubashir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 16:05:21