Копирование файлов и папок, соответствующих критериям, с помощью shutil - PullRequest
0 голосов
/ 22 сентября 2019

Я пытаюсь взять весь каталог файлов и скопировать их в новое место, только если они находятся в списке допустимых файлов.Я не могу понять, как создать каталоги в новом месте, а затем скопировать файлы.


import os, shutil

'''
    For the given path, get the List of all files in the directory tree
'''

def getListOfFiles(dirName):
    # create a list of file and sub directories
    # names in the given directory
    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
        else:
            allFiles.append(fullPath)

    return allFiles        

#list of file paths that we want to  fopy over
acceptable_files = ['/folder1/file1.html', '/file2.csv','/folder1/folder2/file3.html']

def main():

    dirName = 'source_folder';

    # Get the list of all files in directory tree at given path
    listOfFiles = getListOfFiles(dirName)

    # Print the files
    for elem in listOfFiles:
        print(elem)

    print ("****************")

    # Get the list of all files in directory tree at given pat

    for (dirpath, dirnames, filenames) in os.walk(dirName):
        listOfFiles += [os.path.join(dirpath, file) for file in filenames]


    #Loop through files 
    for elem in listOfFiles:
        #determine if file is one that we want to copy
        if elem in acceptable_files:
            #copy over file, ***need to figure out how to create new directories on the fly***
            shutil.copy(elem, 'new_folder')



if __name__ == '__main__':
    main()
...