溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

linux下python多線程如何實(shí)現(xiàn)遞歸復(fù)制文件夾及文件夾中的文件

發(fā)布時間:2021-06-10 11:47:10 來源:億速云 閱讀:488 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下linux下python多線程如何實(shí)現(xiàn)遞歸復(fù)制文件夾及文件夾中的文件,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

本文是利用python 復(fù)制文件夾 剛開始寫了一個普通的遞歸復(fù)制文件夾    然后想了想 覺得對io頻繁的程序 threading 線程還比較友好  就寫了個多線程版本的  最惡心人的地方就是路徑  其他都還好吧 

import os
import threading
import multiprocessing
length_of_folder = 0
def copyfile(Path):
if os.path.isdir(Path):
  print("-----------%s" % ("Testfortherading_" + '/' + Path[length_of_folder:]))
  os.makedirs("Testforthreading_" + '/' + Path[length_of_folder:])
filenames = os.listdir(Path)
for filename in filenames:
  if os.path.isdir(Path + '/' + filename):
    #ps = "Testforthreading_" +"/" + Path[length_of_folder:]
    #print("%s" % (ps + '/' + filename))
    #os.mkdir(ps + '/' + filename)
    temp = Path + '/' + filename
    t = threading.Thread(target=copyfile , args=(temp,))
    t.start()
  else:
    f = open(Path + '/' + filename , 'rb')
    content = f.read()
    F = open('Testforthreading_' + '/' + Path[length_of_folder:]+ '/' + filename , 'wb')
    F.write(content)
    f.close()
    F.close()
def main():
""""""
foldername = input("Please input the folder you want to copy:")
length_of_folder = len(foldername)
if os.path.isdir("Testforthreading_"):
  os.removedirs("Testforthreading_")
os.mkdir("Testforthreading_")
copyfile(foldername)
#p = multiprocessing.Pool(10)
#que = multiprocessing.Manager().Queue()
if __name__ == "__main__":
main()

ps:Python多進(jìn)程遞歸復(fù)制文件夾中的文件

import multiprocessing
import os
import reimport time
# 源文件夾地址、目標(biāo)文件夾地址
SOUR_PATH = ""
DEST_PATH = ""
# 源文件列表 文件夾列表
SOUR_FILE_LIST = list()
SOUR_DIR_LIST = list()
def traverse(source_path):
  """遞歸遍歷源文件夾,獲取文件夾列表、文件列表
  :param source_path: 用戶指定的源路徑
  """
  if os.path.isdir(source_path):
    SOUR_DIR_LIST.append(source_path)
    for temp in os.listdir(source_path):
      new_source_path = os.path.join(source_path, temp)
      traverse(new_source_path)
  else:
    SOUR_FILE_LIST.append(source_path)
def copy_files(queue, sour_file, dest_file):
  """復(fù)制文件列表中的文件到指定文件夾
  :param queue: 隊列,用于監(jiān)測進(jìn)度
  :param sour_file:
  :param dest_file:
  """
  # time.sleep(0.1)
  try:
    old_f = open(sour_file, "rb")
    new_f = open(dest_file, "wb")
  except Exception as ret:
    print(ret)
  else:
    content = old_f.read()
    new_f.write(content)
    old_f.close()
    new_f.close()
  queue.put(sour_file)
def main():
  source_path = input("請輸入需要復(fù)制的文件夾的路徑:\n")
  SOUR_PATH = source_path
  DEST_PATH = SOUR_PATH + "[副本]"
  # dest_path = input("請輸入目標(biāo)文件夾路徑")
  # DEST_PATH = dest_path
  print(">>>源文件夾路徑:", SOUR_PATH)
  print(">目標(biāo)文件夾路徑:", DEST_PATH)
  print("開始計算文件...")
  queue = multiprocessing.Manager().Queue()
  po = multiprocessing.Pool(5)
  traverse(source_path)
  print("創(chuàng)建目標(biāo)文件夾...")
  for sour_dir in SOUR_DIR_LIST:
    dest_dir = sour_dir.replace(SOUR_PATH, DEST_PATH)
    try:
      os.mkdir(dest_dir)
    except Exception as ret:
      print(ret)
    else:
      print("\r目標(biāo)文件夾 %s 創(chuàng)建成功" % DEST_PATH, end="")
  print()
  print("開始復(fù)制文件")
  for sour_file in SOUR_FILE_LIST:
    dest_file = sour_file.replace(SOUR_PATH, DEST_PATH)
    po.apply_async(copy_files, args=(queue, sour_file, dest_file))
  count_file = len(SOUR_FILE_LIST)
  count = 0
  while True:
    q_sour_file = queue.get()
    if q_sour_file in SOUR_FILE_LIST:
      count += 1
    rate = count * 100 / count_file
    print("\r文件復(fù)制進(jìn)度: %.2f%% %s" % (rate, q_sour_file), end="")
    if rate >= 100:
      break
  print()
  ret = re.match(r".*\\([^\\]+)", SOUR_PATH)
  name = ret.group(1)
  print("文件夾 %s 復(fù)制完成" % name)
if __name__ == '__main__':
  main()

以上是“l(fā)inux下python多線程如何實(shí)現(xiàn)遞歸復(fù)制文件夾及文件夾中的文件”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI