Skip to content

Instantly share code, notes, and snippets.

@tanmaychimurkar
Created October 28, 2022 07:05
Show Gist options
  • Save tanmaychimurkar/9641d0b6c8cedea582294940a8990fa6 to your computer and use it in GitHub Desktop.
Save tanmaychimurkar/9641d0b6c8cedea582294940a8990fa6 to your computer and use it in GitHub Desktop.
A short python script to recursively search for files starting with a name and a format, and then move them to a destination folder
import os
import shutil
import logging
logging.basicConfig(format='%(levelname)s:%(name)s: %(message)s (%(asctime)s; %(filename)s:%(lineno)d)',
datefmt='%Y-%m-%d %H:%M:%S',
level=logging.INFO)
LOGGER = logging.getLogger(__name__)
# Define the name of the file starts with, the file format, and the directory where the files need to be moved into
STARTS_WITH = 'test'
FILE_FORMAT = '.pkl'
DIRECTORY_TO_LOOK_INTO = 'usr_directory_to_look_into_for_files'
DIRECTORY_TO_MOVE_INTO = 'usr_directory_to_move_files_into'
file_matches = []
for root_directory, _, filenames in os.walk(DIRECTORY_TO_LOOK_INTO):
for filename in filenames:
if filename.startswith(STARTS_WITH) and filename.endswith(FILE_FORMAT):
LOGGER.info(f'Found a file that starts with `{STARTS_WITH}` and has the format `{FILE_FORMAT}` in directory'
f' `{root_directory}`')
file_matches.append(os.path.join(root_directory, filename))
LOGGER.info(f'The following files have been matched with the description:\n')
LOGGER.info(file_matches)
for file_location in file_matches:
shutil.copy(file_location, DIRECTORY_TO_MOVE_INTO)
LOGGER.info(f'All the files matching the provided description have been moved to the directory '
f'`{DIRECTORY_TO_MOVE_INTO}`')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment