簡體   English   中英

"如何跳過子文件夾中的現有文件並僅復制新文件"

[英]How to skip existing files in sub folders and copy only new files

我使用shutil copytree復制文件夾和主文件夾內的所有子文件夾

import shutil
import sys
import os
import re

SOURCE_FOLDER = sys.argv[1]
DESTINATION_FOLDER = sys.argv[2]


def copyDirectory(SOURCE_FOLDER, DESTINATION_FOLDER):
    try:
        print SOURCE_FOLDER
        print DESTINATION_FOLDER
        shutil.copytree(SOURCE_FOLDER, DESTINATION_FOLDER)
    # Directories are the same
    #except:
    #   print "Not copied"
    except shutil.Error as e:
        print('Directory not copied. Error: %s' % e)
    # Any error saying that the directory doesn't exist
    except OSError as e:
        print('Directory not copied. Error: %s' % e)

copyDirectory(SOURCE_FOLDER,DESTINATION_FOLDER)

shutil.copytree不是為了跳過現有的目標文件和目錄而編寫的。 從文檔

目標目錄必須不存在。

您將需要編寫自己的解決方案。 現有的copytree代碼是一個好的開始。

為了檢查目錄是否已經存在,您可以使用: os.path.exists(directory)

if not os.path.exists(DESTINATION_FOLDER):
    shutil.copytree(SOURCE_FOLDER, DESTINATION_FOLDER)

如果 dest 目錄已經存在,您可以在 src-dir 的子目錄上運行您的函數。 您可以使用以下函數獲取所有 src-dir 子目錄的列表,該函數獲取目錄名稱作為輸入,並返回子目錄列表

def SubDirPath (d):
    return filter(os.path.isdir, [os.path.join(d,f) for f in os.listdir(d)])

使用此目錄列表,您可以在目錄的每個實例上再次執行您的功能。

對於同時存在於 : src 和 dst 中的每個目錄 - 您需要檢查 src-dir 中的每個文件,如果該文件也存在於 dst-dir 中。

此致,

亞龍

使用python3<\/code> ,您可以使用shutil.copytree<\/code>和一個選項來忽略現有的 dirs 錯誤:

shutil.copytree(SOURCE_FOLDER, DESTINATION_FOLDER, dirs_exist_ok=True)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM