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

Python利用队列广度遍历、复制文件

2018-01-09 20:07 429 查看
"""
广度遍历目录、复制文件
"""
import os
import collections

"""
@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 = collections.deque()
#创建一个队列用来存放目标路径
queueTarPath = collections.deque()
#将路径存进队列
queuePath.append(sourcePath)
#将目标文件路径存进队列
queueTarPath.append(targetPath)

while True:

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

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

#遍历出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__':

sourcePath = r"原文件路径"
targetPath = r"目标文件路径"
getDirAndCopyFile(sourcePath,targetPath)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 遍历 os