使用shuti复制符合条件的文件和文件夹

2024-04-23 19:07:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图获取一个完整的文件目录,并将它们复制到一个新位置,前提是它们位于可接受的文件列表中。我不知道如何在新位置创建目录,然后再复制文件


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()

Tags: ofthepathinforosfilesall