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:
= os.path.join(dir_path, "".join(["*", file_ext]))
file_query # Run glob (note, always returns a list even when empty):
= glob.glob(file_query)
file_list 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
= argparse.ArgumentParser(
p ="Renames all files of given file extension.")
description
# Add an additional optional argument for folder path and file extension
# the default (if not given) will be to look locally.
"-p", "--path", default=".",
p.add_argument(help="Path to your files")
"-e", "--ext", default=".txt",
p.add_argument(help="Desired file type (e.g., .txt)")
"-t", "--test", action="store_true",
p.add_argument(help="Run in test mode; no actions")
# Read any commandline arguements sent to the program
# NOTE: if -h or --help, the program stops here
= p.parse_args()
args
if not args.test:
print("Renaming files...")
# Find files
= find_files(args.path, args.ext)
my_files 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
= os.path.basename(my_file)
old_name
# Define the regular expression for substitution
# presently looking for the underscore character
= re.compile("_")
p
# Run the string substitution, replacing "_" with "-"
# https://docs.python.org/3/howto/regex.html#search-and-replace
= p.sub("-", old_name)
new_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!
= os.path.join(args.path, new_name)
new_path
os.rename(my_file, new_path)
if not args.test:
print("... complete!")