涉及的知識點
1. os.mkdir(path) # os模塊的功能,在指定路徑上創建文件夾
os.listdir(path) # os模塊的功能,打開指定文件夾裏面的內容,返回一個列表,該文件夾裏面的所有文件都在列表裏面
2. pool = multiprocessing.Pool(5) # 創建一個進程池,最大進程數爲5
q = multiprocessing.Manager().Queue() # 創建一個隊列 ,(注意是Manager裏面的Queue()方法)
po.apply_async(要調用的目標,(傳遞給目標的參數元組,))
po.close() # 關閉進程池,關閉後po不再接受新的請求
代碼如下:
我要拷貝的文件夾: D:\shuju\文件Copy器
'''文件Copy (多進程)'''
import os
import multiprocessing
def copy_file(q, file_name, original_document, new_file):
'''文件的複製'''
with open(original_document + "/" + file_name, "rb") as od_f:
content = od_f.read()
with open(new_file + "/" + file_name, "wb") as new_f:
new_f.write(content)
'''如果拷貝完了文件,那麼就向隊列中寫入一個消息,表示已經完成'''
q.put(file_name)
def main():
'''獲取用戶要copy的文件夾的名字 original_document'''
original_document = input("請輸入原始文件夾的名字:")
'''2.創建一個新的文件夾 new_file'''
try:
new_file = original_document + "(副本)"
os.mkdir(new_file)
except Exception:
pass
'''獲取文件夾的所有待copy的文件名字 (os.listdir())'''
file_list = os.listdir(original_document)
'''創建進程池'''
pool = multiprocessing.Pool(5)
'''創建一個隊列'''
q = multiprocessing.Manager().Queue()
'''複製原文件夾中的文件,到新文件夾中的文件'''
for file in file_list:
pool.apply_async(copy_file, args=(q, file, original_document, new_file))
pool.close()
all_file_num = len(file_list) # 所有文件的個數
copy_complete = 0
while True:
q.get() # 獲取文件數據
copy_complete += 1
print("\r拷貝的進度:%.f %%" % (copy_complete * 100 / all_file_num),end="")
if copy_complete >= all_file_num:
break
print() # 換行
print("拷貝完成")
if __name__ == '__main__':
main()
運行結果:
請輸入原始文件夾的名字:D:\shuju\文件Copy器
拷貝的進度:100 %
拷貝完成
打開文件夾就會有:
裏面的文件一個不少