Search code examples
pythonpyhook

How to find files and save them to different folder in python


I amt trying to find all relevant files and folders from local repository. e.g. I pulled projects from git to my local machine and I want to search for specific files(.txt) and save them to new folder in same pattern (root->dir-> file). Basically I want to get rid of any files which doesn't match name and extension but keep the same format. Thanks in advance.


Solution

  • You can traverse the directory tree finding the files you want with this:

    import os, fnmatch
    
    def find_files(directory, pattern):
        for root, dirs, files in os.walk(directory):
            for basename in files:
                if fnmatch.fnmatch(basename, pattern):
                    filename = os.path.join(root, basename)
    
                    yield filename
    
    def find_files_to_list(directory, pattern):
        file_list = []
        for root, dirs, files in os.walk(directory):
            for basename in files:
                if fnmatch.fnmatch(basename, pattern):
                    filename = os.path.join(root, basename)
                    file_list.append(filename)
    
        return file_list
    

    then copy the repository and do something like this:

    wanted_files = find_files_to_list('/original_project/', '*.html')
    for filename in find_files('/copy_project/', '*'):
        if filename not in wanted_files:
            os.remove(filename)