需求:
實現文件夾拷貝功能(包括文件內的文件),並打印拷貝進度
模塊:
利用 os模塊
multiprocessing 模塊
import multiprocessing
import os
def deal_file(old_dir,new_dir,file_name,queue):
# 打開以存在文件
old_file = open(os.path.join(old_dir,file_name),"rb")
# 創建新文件
new_file = open(os.path.join(new_dir,file_name),"wb")
# 循環將內容寫入新文件
while True:
# 單行讀取
data = old_file.readline()
# 如果有內容寫入否則退出
if data:
new_file.write(data)
else:
break
# 關閉文件
old_file.close()
new_file.close()
# 向隊列中添加值用以計數,參數可填任意值
queue.put(file_name)
def main():
# 創建用戶輸入文件的備份
old_dir = input("請輸入文件名:")
new_dir = "備份"+old_dir
os.mkdir(new_dir)
# 列出文件夾內的文件列表
file_list = os.listdir(old_dir)
queue = multiprocessing.Queue(128)
for file_name in file_list:
pro = multiprocessing.Process(target=deal_file,args=(old_dir,new_dir,file_name,queue))
# 創建子進程
pro.start()
# 定義變量用以計數
num = 0
while True:
# 取出隊列中的值
queue.get()
# 計數器+1
num += 1
# 打印下載進度
print("\r文件已下載%.2f %%" % (num/len(file_list)*100),end="")
# 如果計數等於文件長度提示完成退出
if num == len(file_list):
print("文件下載完成")
break
if __name__ == "__main__":
main()