如何用Python将文件夹/文件复制到目录上一级路径?
解决方案
首先修正你的导入代码,正确的os导入方式是import os,而非from utils import os。以下针对两种需求场景提供实现代码:
场景1:复制整个1.0文件夹到上一级,并重命名为2.0
如果需要把1.0整个文件夹复制到上一级目录(即C:\Users\remco\Downloads\stikstof-master),同时命名为2.0,可使用以下代码:
import os import shutil # 获取当前脚本所在路径(假设脚本在1.0文件夹内) current_dir = os.getcwd() # 上一级目录路径 parent_dir = os.path.dirname(current_dir) # 目标文件夹路径 target_dir = os.path.join(parent_dir, "2.0") # 复制整个文件夹(Python3.8+支持dirs_exist_ok=True,若目标已存在则覆盖) shutil.copytree(current_dir, target_dir, dirs_exist_ok=True) print(f"已成功将{current_dir}复制到{target_dir}")
场景2:仅复制1.0文件夹内的所有文件到上一级的2.0文件夹
如果只需要把1.0里的20个文件复制到上一级新创建的2.0文件夹中,代码如下:
import os import shutil current_dir = os.getcwd() parent_dir = os.path.dirname(current_dir) target_dir = os.path.join(parent_dir, "2.0") # 创建目标文件夹(若已存在则跳过) os.makedirs(target_dir, exist_ok=True) # 遍历1.0内的所有文件并复制 for filename in os.listdir(current_dir): source_file = os.path.join(current_dir, filename) # 仅处理文件,跳过子文件夹 if os.path.isfile(source_file): shutil.copy(source_file, target_dir) print(f"已复制:{filename}") print("所有文件复制完成")
注意事项
- 确保脚本拥有读取源文件、写入目标路径的权限
- 如果目标文件夹已存在,
shutil.copytree在未设置dirs_exist_ok=True时会报错,需根据需求选择是否覆盖
内容的提问来源于stack exchange,提问作者Remco
相关产品推荐
相关产品推荐

