Fundamentals 5 min read

Python Script to Search and Move Files by Extension with Command-Line Arguments

This article demonstrates how to write a Python program that recursively searches a specified directory for files of a given extension (e.g., PNG), moves the found files to a target directory, and later adapts the script to accept command‑line parameters for flexible execution.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Script to Search and Move Files by Extension with Command-Line Arguments

The tutorial begins by describing a sample file structure: a folder D:\pic1 containing several PNG images (including nested subfolders) and an empty destination folder D:\ABC\pic2 . The goal is to locate all PNG files under D:\pic1 and move them to the destination.

Two functions are defined: search_file(root, target) recursively walks through the directory tree, collects full paths of files whose extension matches target , and handles PermissionError to avoid crashes; move_file(file_list, dest) iterates over the collected paths and moves each file to dest using shutil.move , printing any errors.

import os, shutil
file_list = []
# search function
def search_file(root, target):
    for file in os.listdir(root):
        path = root
        try:
            path = path + os.sep + file
            if os.path.isdir(path):
                search_file(path, target)
            else:
                if file.split('.')[-1] == target:
                    file_list.append(path)
        except PermissionError as e:
            print(e)
    return file_list

# move function
def move_file(file_list, dest):
    for file in file_list:
        try:
            shutil.move(file, dest)
        except shutil.Error as e:
            print(e)

# main entry
def main():
    root = "D:\\pic1"
    target = "png"
    dest_dir = "D:\\ABC\\pic2"
    result = search_file(root, target)
    print(result)
    move_file(result, dest_dir)

if __name__ == '__main__':
    main()

After running the script, the PNG files are successfully relocated, as shown by the accompanying screenshots.

The article then extends the script to accept command‑line arguments, allowing users to specify the source directory, file extension, and destination directory when invoking the program.

import sys
import os, shutil
file_list = []
# search function with filename argument
def search_file(root, file_name):
    for file in os.listdir(root):
        path = root
        try:
            path = path + os.sep + file
            if os.path.isdir(path):
                search_file(path, file_name)
            else:
                if file.split('.')[-1] == file_name:
                    file_list.append(path)
        except PermissionError:
            pass
    return file_list

def move_file(file_list, dest):
    for file in file_list:
        shutil.move(file, dest)

def main(argv):
    root = argv[1]
    target = argv[2]
    dest_dir = argv[3]
    result = search_file(root, target)
    print(result)
    move_file(result, dest_dir)

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

To execute, open a command prompt, navigate to the script’s directory, and run: python demo.py D:\\pic1 png D:\\ABC\\pic2 . The program prints the list of found files and moves them accordingly, as demonstrated by the final screenshots.

pythonrecursioncommand-linescriptingfile-searchfile-move
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.