import os old_dir = r"F:\千峰Python\python1704\day08" new_dir = r"F:\千峰Python\python1704\day08888888" #文件操作 def file_operation(old_dir,new_dir,names): dict_old = os.path.join(old_dir,names) dict_new = os.path.join(new_dir,names) file1 = open(dict_old,"rb") file2 = open(dict_new,"wb") file2.write(file1.read()) file2.flush() file1.close() file2.close() def copy_dir(new_dir,old_dir): list1 = os.listdir(old_dir) for name in list1: #判断是文件还是目录 if os.path.isdir(os.path.join(old_dir,name)): #index == -1 or index == 0 # 是目录 print("目录") dir_dir_old = os.path.join(old_dir,name) dir_dir_new = os.path.join(new_dir,name) os.mkdir(dir_dir_new) copy_dir(dir_dir_new,dir_dir_old) else: # 是文件 print("文件") file_operation(old_dir,new_dir,name) #生成一个新目录 os.mkdir(new_dir) copy_dir(new_dir,old_dir)
#2.广度遍历(队列) # 创建空队列 # 1.将根目录加载进对队列 # 2.取出队列元素 # 3.遍历目录下一层的文件和目录,若文件复制,若目录压入队列 # 4.队列无元素,关闭文件 import os from collections import deque old_dir = r"F:\千峰Python\python1704\day08-文件,目录,路径操作" new_dir = r"F:\千峰Python\python1704\day08-复制品" def file_operation(old_dir,new_dir): file1 = open(old_dir,"rb") file2 = open(new_dir,"wb") while True: rf = file1.read(1024*1024) if len(rf) == 0: file1.close() file2.close() break file2.write(rf) file2.flush() #创建两个空队列 queue1 = deque() queue2 = deque() #入队根目录 queue1.append(old_dir) queue2.append(new_dir) #如果目录不存在,则创建 if not os.path.exists(new_dir): os.makedirs(new_dir) while True: if len(queue1) == 0: break file_path1 = queue1.popleft() file_path2 = queue2.popleft() list1 = os.listdir(file_path1) for res in list1: abs_path1 = os.path.join(file_path1,res) abs_path2 = os.path.join(file_path2,res) if os.path.isfile(abs_path1): print("文件操作") file_operation(abs_path1,abs_path2) else: print("目录操作") queue1.append(abs_path1) queue2.append(abs_path2) os.makedirs(abs_path2)
-------------------------------------------------------------------------------------------------------- #3.深度遍历 import os from collections import deque old_dir = r"F:\千峰Python\python1704\day08-文件,目录,路径操作" new_dir = r"F:\千峰Python\python1704\day08-复制品" def file_operation(old_dir,new_dir): file1 = open(old_dir,"rb") file2 = open(new_dir,"wb") while True: rf = file1.read(1024*1024) if len(rf) == 0: file1.close() file2.close() break file2.write(rf) file2.flush() #创建两个空栈 stack1 = [] stack2 = [] #入栈根目录 stack1.append(old_dir) stack2.append(new_dir) #如果目录不存在,则创建 if not os.path.exists(new_dir): print("1111") os.makedirs(new_dir) while True: if len(stack1) == 0: break file_path1 = stack1.pop() file_path2 = stack2.pop() list1 = os.listdir(file_path1) for res in list1: abs_path1 = os.path.join(file_path1,res) abs_path2 = os.path.join(file_path2,res) if os.path.isfile(abs_path1): print("文件操作") file_operation(abs_path1,abs_path2) else: print("目录操作") stack1.append(abs_path1) stack2.append(abs_path2) os.makedirs(abs_path2)