Bio
Engineer, programmer, educator. I enjoy playing guitar, baking bread, and writing application-based computer programs in Perl, R, C++, Arduino, and Python.
Websites:

Sample script

rename (.py)

I wrote this script because I made a mistake naming all the files in the organization repository with underscores. It seems the world-wide web actually prefers dashes between words. I had an old Perl script that could do this and I wanted to try my hand at transcribing it to Python, so here we go!

See also my Music Randomizer (.py) for those in need of a better MP3 shuffle.

Enjoy!

#!/usr/bin/env python3
#
# rename.py
#
# VERSION 0.1
#
# LAST EDIT: 2020-08-18
#
# Renames files in a folder based on a regular expression.
# In this example, it changes all underscores (_) to dashes (-).
#
##############################################################################
# REQUIRED MODULES
##############################################################################
import argparse
import glob
import os
import os.path
import re


##############################################################################
# FUNCTIONS
##############################################################################
def find_files(dir_path, file_ext):
    """
    Name:     find_files
    Inputs:   - str, directory path (dir_path)
              - str, file extension (file_ext)
    Outputs:  list, file paths
    Features: Searches directory for files of a given type.
    """
    # Define a glob query:
    file_query = os.path.join(dir_path, "".join(["*", file_ext]))
    # Run glob (note, always returns a list even when empty):
    file_list = glob.glob(file_query)
    return file_list


##############################################################################
# MAIN
##############################################################################
if __name__ == "__main__":
    # Create an ArgumentParser class object for dealing with commandline args
    # https://docs.python.org/3.7/howto/argparse.html
    p = argparse.ArgumentParser(
        description="Renames all files of given file extension.")

    # Add an additional optional argument for folder path and file extension
    # the default (if not given) will be to look locally.
    p.add_argument("-p", "--path", default=".",
                   help="Path to your files")
    p.add_argument("-e", "--ext", default=".txt",
                   help="Desired file type (e.g., .txt)")
    p.add_argument("-t", "--test", action="store_true",
                   help="Run in test mode; no actions")

    # Read any commandline arguements sent to the program
    # NOTE: if -h or --help, the program stops here
    args = p.parse_args()

    if not args.test:
        print("Renaming files...")

    # Find files
    my_files = find_files(args.path, args.ext)
    for my_file in my_files:
        # I only want to change file names, not path names!
        # so save the basename w/o it's associated path before sub
        old_name = os.path.basename(my_file)

        # Define the regular expression for substitution
        # presently looking for the underscore character
        p = re.compile("_")

        # Run the string substitution, replacing "_" with "-"
        # https://docs.python.org/3/howto/regex.html#search-and-replace
        new_name = p.sub("-", old_name)

        if args.test:
            # Just print, no actions taken in test mode
            if old_name != new_name:
                print("{}\t{}\t{}".format(args.path, old_name, new_name))
        else:
            if old_name != new_name:
                # Perform file renaming; remember the file path!
                new_path = os.path.join(args.path, new_name)
                os.rename(my_file, new_path)

    if not args.test:
        print("... complete!")