用python复制文件

1. 根据文件夹的名称复制

需要复制的文件夹编号文件中,每一行表示一个编号,如下所示:

> cat id.txt
1
2
3
...
>

目标文件的目录结构树如下所示:

  • Normal_data

    • T1Img

      • 23XIAOHEI
      • 432XIAOMING
    • T1ImgSegment
      • 23XIAOHEI
      • 432XIAOMING
    • T1ImgSegmentS
      • 23XIAOHEI
      • 432XIAOMING
    • T1Raw
      • 23XIAOHEI
      • 432XIAOMING

主要流程就是先从文件中读到要复制的文件的编号,然后遍历目标文件夹,从文件夹名称中切分出编号,然后进行复制操作。完整的代码如下:

# -*- coding: utf-8 -*-
# @Time : 2018/6/6 20:33
# @Author : sangf
# @desc : copy the t1 image by id
# if you want to know which id is not found, you should input the command 'python3 copyT1ById.py >> not_found.txt' in shell.
# And you will find the new file named 'not_found.txt' in which there are maybe some ids or not.
# If it is empty, all image have been found; and if not, those is not be found.
# Good luck!
import os
import shutil
import re # must set those value
SRC_PATH = r'/home/admin/MRI_DATA/T1/Normal_data'
DST_PATH = r'/home/admin/Desktop/xxx'
ID_FILE_PATH = r'/home/admin/MRI_DATA/T1/xxx.txt'
TYPE = r'T1Raw' def cutIdInFloderName(floderName):
'''
' cut out the id in floderName.
' Don't change this function.
'''
idIndex = floderName.index(re.search(r'[A-Za-z]', floderName).group())
id = floderName[0:idIndex]
return id def indexDict(srcPath, typeData):
'''
' building the index dict.
' example: {path, id}.
' Don't change this function.
'''
tmpIndexDict = {}
for tmpYearFloder in os.listdir(srcPath):
tmpYearFloderPath = os.path.join(srcPath, tmpYearFloder)
tmpTypeFloderPath = os.path.join(tmpYearFloderPath, typeData)
for tmpSubFloder in os.listdir(tmpTypeFloderPath):
tmpSubFloderPath = os.path.join(tmpTypeFloderPath, tmpSubFloder)
tmpIndexDict[tmpSubFloderPath] = cutIdInFloderName(tmpSubFloder)
# end for
# end for
return tmpIndexDict def findPathInDict(tmpIndexDict, tmpId):
'''
' find the path from indexDict.
' if not found, the size of return is 0
' Please don't change the function.
'''
tmpFindedPath = []
for tmpKey in tmpIndexDict.keys():
if tmpIndexDict[tmpKey] == tmpId:
tmpFindedPath.append(tmpKey)
# end if
# end for
return tmpFindedPath def main(tmpSrcPath, tmpDstPath, tmpIdFilePath, tmpType):
'''
' the main function.
' this function is the controller of the program.
' so it is very import to keep this function is not be changed.
' lol...
'''
idList = []
with open(tmpIdFilePath, 'r') as f:
for line in f.readlines():
line = line.replace('\n', '')
# print(line)
# avoid the same id in id list
try:
idList.index(line)
except ValueError:
idList.append(line)
# end for
# end open
# build index
indexs = indexDict(tmpSrcPath, tmpType)
# find the path
for tmpId in idList:
paths = findPathInDict(indexs, tmpId)
if len(paths) == 0:
# print not found
print(tmpId)
else:
# copy
for tmpPath in paths:
tmpSplitPath = tmpPath.split('/')
tmpDstCmpltPath = os.path.join(tmpDstPath, tmpSplitPath[-3], tmpSplitPath[-2], tmpSplitPath[-1])
# print(tmpDstCmpltPath)
shutil.copytree(tmpPath, tmpDstCmpltPath)
# end if
# end for # the start of the program
main(SRC_PATH, DST_PATH, ID_FILE_PATH, TYPE)

2. 根据文件夹的名称复制并重命名

流程与上述流程类似,代码如下:

# -*- coding: utf-8 -*-
# @Time : 2018/6/6 20:33
# @Author : sangf
# @desc : copy the t1 image by id, and rename the floder
# if you want to know which id is not found, you should input the command 'python3 copyT1ById.py >> not_found.txt' in shell.
# And you will find the new file named 'not_found.txt' in which there are maybe some ids or not.
# If it is empty, all image have been found; and if not, those is not be found.
# Good luck!
import os
import shutil
import re # must set those value
SRC_PATH = r'/home/admin/MRI_DATA/T1/Normal_data'
DST_PATH = r'/home/admin/Desktop/xxx'
ID_FILE_PATH = r'/home/admin/Desktop/xxx.txt'
TYPE = r'T1Raw' def cutIdInFloderName(floderName):
'''
' cut out the id in floderName.
' Don't change this function.
'''
idIndex = floderName.index(re.search(r'[A-Za-z]', floderName).group())
id = floderName[0:idIndex]
return id def indexDict(srcPath, typeData):
'''
' building the index dict.
' example: {path, id}.
' Don't change this function.
'''
tmpIndexDict = {}
for tmpYearFloder in os.listdir(srcPath):
tmpYearFloderPath = os.path.join(srcPath, tmpYearFloder)
tmpTypeFloderPath = os.path.join(tmpYearFloderPath, typeData)
for tmpSubFloder in os.listdir(tmpTypeFloderPath):
tmpSubFloderPath = os.path.join(tmpTypeFloderPath, tmpSubFloder)
tmpIndexDict[tmpSubFloderPath] = cutIdInFloderName(tmpSubFloder)
# end for
# end for
return tmpIndexDict def findPathInDict(tmpIndexDict, tmpId):
'''
' find the path from indexDict.
' if not found, the size of return is 0
' Please don't change the function.
'''
tmpFindedPath = []
for tmpKey in tmpIndexDict.keys():
if tmpIndexDict[tmpKey] == tmpId:
tmpFindedPath.append(tmpKey)
# end if
# end for
return tmpFindedPath def main(tmpSrcPath, tmpDstPath, tmpIdFilePath, tmpType):
'''
' the main function.
' this function is the controller of the program.
' so it is very import to keep this function is not be changed.
' lol...
'''
idList = []
with open(tmpIdFilePath, 'r') as f:
for line in f.readlines():
line = line.replace('\n', '')
# print(line)
# avoid the same id in id list
try:
idList.index(line)
except ValueError:
idList.append(line)
# end for
# end open
# build index
indexs = indexDict(tmpSrcPath, tmpType)
# find the path
for tmpId in idList:
oldIdInLine, newIdInLine = tmpId.split(',')
paths = findPathInDict(indexs, oldIdInLine)
if len(paths) == 0:
# print not found
print(oldIdInLine)
# pass
else:
# copy
postfix = 1
for tmpPath in paths:
tmpSplitPath = tmpPath.split('/')
if len(paths) > 1:
newIdInLine = newIdInLine.split('-')[0] + '-' + str(postfix)
postfix += 1
tmpDstCmpltPath = os.path.join(tmpDstPath, tmpSplitPath[-2], newIdInLine)
# print(tmpDstCmpltPath)
shutil.copytree(tmpPath, tmpDstCmpltPath)
# end if
# end for # the start of the program
main(SRC_PATH, DST_PATH, ID_FILE_PATH, TYPE)

用python复制文件夹的更多相关文章

  1. python 中文件夹的操作

    文件有两个管家属性:路径和文件名. 路径指明了文件在磁盘的位置,文件名原点的后面部分称为扩展名(后缀),它指明了文件的类型. 一:文件夹操作 Python中os 模块可以处理文件夹 1,当前工作目录 ...

  2. 用Python复制文件的9个方法

    Python 中有许多"开盖即食"的模块(比如 os,subprocess 和 shutil)以支持文件 I/O 操作.在这篇文章中,你将会看到一些用 Python 实现文件复制的 ...

  3. 用Python复制文件的9个方法(转)

    转自:https://zhuanlan.zhihu.com/p/35725217 用Python复制文件的9个方法 Python 中有许多“开盖即食”的模块(比如 os,subprocess 和 sh ...

  4. JAVA实现复制文件夹

    package com.filetest; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; impor ...

  5. CMD复制文件夹

    CMD复制文件夹 xcopy /E/I/Y "D:\GitHub\WIP\app" "D:\GitHub\WIP_server\html\webshell"

  6. python 遍历文件夹 文件

    python 遍历文件夹 文件   import os import os.path rootdir = "d:\data" # 指明被遍历的文件夹 for parent,dirn ...

  7. Web 在线文件管理器学习笔记与总结(13)重命名文件夹(14)复制文件夹

    (13)重命名文件夹 ① 重命名文件夹通过 rename($oldname,$newname) 实现 ② 检测文件夹名是否符合规范 ③ 检测当前目录中是否存在同名文件夹名称,如果不存在则重命名成功 i ...

  8. c# 封装的文件夹操作类之复制文件夹

    c#  封装的文件夹操作类之复制文件夹 一.复制文件夹原理: 1.递归遍历文件夹 2.复制文件 二.FolderHelper.cs /// <summary> /// 文件夹操作类 /// ...

  9. python 关于文件夹的操作

    在python中,文件夹的操作主要是利用os模块来实现的, 其中关于文件夹的方法为:os.lister() , os.path.join() , os.path.isdir() #  path 表示文 ...

随机推荐

  1. 【MySQL】大白话讲讲主从架构的几种搭配方式详解

    话不多,直接上图: 主要来详细讲讲各个搭配 1>一主一从(成本最低): 并不是用来提高程序性能的,主要是用来做数据的热备(即如果master节点挂掉的话,slave节点能充当master节点), ...

  2. 【数据分析入门】之Spyder中如何让图表单独显示出来

    一般图表只显示在ipython console中,且是静态,无法进行放大,移动等操作解决方案:[win]tools——preferences——ipython console——graphics中ba ...

  3. 项目中 SimpleDateFormat 的正确使用

    项目中 SimpleDateFormat 的正确使用 日常开发中,我们经常需要使用时间相关类,说到时间相关类,想必大家对 SimpleDateFormat 并不陌生.主要是用它进行时间的格式化输出和解 ...

  4. springmvc数据处理-中文乱码

    首先解决中文乱码 通过mvc过滤器解决,在web.xml中配置 <filter> <filter-name>CharacterEncodingFilter</filter ...

  5. js数组对象的一些常用方法

    pop:删除数组最后一个元素 语法: array.pop(); 如 var array = ['1','2','3']; array.pop(); 返回结果:[‘1’,‘2’]此方法会改变数组的长度 ...

  6. vue中使用vue-qrcode生成二维码

    要使用二维码,引入一个包就可以了,使用非常简单,话不多说,看代码吧 //1,引入, import VueQrcode from '@xkeshi/vue-qrcode'; Vue.component( ...

  7. webpack-dev-server 使用 react-router 启用 browserhistory 采坑记

    问题的产生 今天下午请假,忙完手头事之后,在家实在无聊,想着从0开始搭建一个 react 的项目.webpack 基本配置之前研究过,没什么大问题.谁想,在 react-router 的配置时出现了个 ...

  8. Java IO(八) PipedInputStream 和 PipedOutputStream

    Java IO(八) PipedInputStream 和 PipedOutputStream 一.介绍 PipedInputStream 和 PipedOutputStream 是管道输入流和管道输 ...

  9. Jpa使用详解

    目录 ORM思想 1.ORM概述 2.为什么要使用ORM 3.常见的ORM框架 JPA简介 1.JPA概述 2.JPA的优势 3.JPA与hibernate的关系 JPA入门案例 1.搭建开发环境 常 ...

  10. 本地安装JDK1.7和1.8,可相互快速切换

    1.JDK官网下载jdk1.7和jdk1.8 https://www.oracle.com/java/technologies/javase-jdk8-downloads.html 2.将jdk1.7 ...