您的位置:首页 > 编程语言 > Python开发

Python利用列表深度遍历目录、复制文件

2018-01-09 20:17 501 查看
"""
@深度遍历目录、复制文件
"""
import os
"""
@para1   sourcePath原文件目录
@para1   targetPath目标文件目录
"""

def getDirAndCopyFile(sourcePath,targetPath):

if not os.path.exists(sourcePath):
return

if not os.path.exists(targetPath):
os.makedirs(targetPath)
tempTar = targetPath
#创建一个列表来存放路径
queuePath = []
#创建一个列表用来存放目标路径
queueTarPath = []
#将路径存进队列
queuePath.append(sourcePath)
#将目标文件路径存进队列
queueTarPath.append(targetPath)

while True:

#如果原文件路径队列为空,则跳出循环
if len(queuePath)==0:
break

#从原文件路径队列中向左取出路径
path = queuePath.pop()
#从目标路径队列中向左取出路径
tarpath=queueTarPath.pop()

#遍历出path
for fileName in os.listdir(path):
#拼接路径
absPath = os.path.join(path,fileName)
absTar = os.path.join(tarpath,fileName)

# 判断是否是文件,是就进行复制
if os.path.isfile(absPath):
rbf = open(absPath, 'rb')
wbf = open(absTar, 'wb')
while True:
content = rbf.readline(1024 * 1024 * 5)
if len(content) == 0:
break
wbf.write(content)
wbf.flush()
rbf.close()
wbf.close()

#如果是路径,则存进队列
if os.path.isdir(absPath):
if os.path.exists(absTar):
os.rmdir(absTar)
os.mkdir(absTar)
queueTarPath.append(absTar)
queuePath.append(absPath)

if __name__ == '__main__':

startTime = time.clock()
sourcePath = r"H:\培训资料"
targetPath = r"H:\培训资料_备份"
getDirAndCopyFile(sourcePath,targetPath)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: