批量文件复制(覆盖)-py
用于单文件复制、大批量指定路径的文件或者大批量指定目录移动的py脚本
需要学习的就是,shutil库的copyfile复制文件,目标路径不存在或者路径有权限,将会报错
import os
from shutil import copyfile
# 目录 -> 目录
def copy_dir(fromDir, toDir):
if fromDir.find("exceptionfolder") > 0:
return
op = os.path
if not op.exists(toDir):
os.makedirs(toDir)
if op.exists(fromDir):
for file in os.listdir(fromDir):
file_path = op.join(fromDir, file)
dst_path = op.join(toDir, file)
if op.isfile(op.join(fromDir, file)):
copyfile(file_path, dst_path)
else:
copy_dir(file_path, dst_path)
# 文件 -> 文件
# copyfile(r'D:\MyDesk\需要迁移的任务列表.txt', 'E:\需要迁移的任务列表.txt')
def copyFiles(sourceFiles):
op = os.path
try:
# 单个文件复制
# D:\GitProjects\mobileOfflineAnalysis\dev\hive\edm\push\sh_edm_push_user_content_full_link_day.sh
# D:\GitProjects\offlineexperiment\dev\hive\edm\push\sh_edm_push_user_content_full_link_day.sh
if isinstance(sourceFiles, str):
if sourceFiles.find("exceptionfolder") > 0:
return
sourceFileName = sourceFiles.split('\\')[-1]
sourceFilePath = sourceFiles[:sourceFiles.index(sourceFileName) - 1]
MidPath = sourceFiles[len(FROMROOT):sourceFiles.index(sourceFileName) - 1]
# print(sourceFileName)
# print(sourceFilePath)
# print(MidPath)
targetFilePath = TOROOT + MidPath
targetFiles = targetFilePath + '\\' + sourceFileName
if not op.exists(targetFilePath):
os.makedirs(targetFilePath)
copyfile(sourceFiles, targetFiles)
elif isinstance(sourceFiles, list):
for sourceFile in sourceFiles:
if sourceFile.find("exceptionfolder") > 0:
return
sourceFileName = sourceFile.split('\\')[-1]
sourceFilePath = sourceFile[:sourceFile.index(sourceFileName) - 1]
MidPath = sourceFile[len(FROMROOT):sourceFile.index(sourceFileName) - 1]
# print(sourceFileName)
# print(sourceFilePath)
# print(MidPath)
targetFilePath = TOROOT + MidPath
targetFiles = targetFilePath + '\\' + sourceFileName
if not op.exists(targetFilePath):
os.makedirs(targetFilePath)
# with open(r'D:\MyDesk\已迁移的文件.txt', encoding='utf-8', mode='a') as file:
# file.write(targetFiles+'\n')
copyfile(sourceFile, targetFiles)
# file.close()
except Exception as b:
print('报错:', sourceFiles)
if __name__ == '__main__':
FROMROOT = r'D:\GitProjects\mobileOfflineAnalysis\dev\hive'
TOROOT = r'D:\GitProjects\offlineexperiment\dev\hive'
sh_list = []
with open(r'D:\MyDesk\需要迁移的任务列表.txt', encoding='utf-8', mode='r') as path_file:
for path in path_file:
sh_list.append(path.replace('\n', ''))
path_file.close()
copyFiles(sh_list)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人