Skip to content

Instantly share code, notes, and snippets.

@andreortiz82
Created March 11, 2024 02:36
Show Gist options
  • Save andreortiz82/cdf59df8d448f7bc8e610d167e650a03 to your computer and use it in GitHub Desktop.
Save andreortiz82/cdf59df8d448f7bc8e610d167e650a03 to your computer and use it in GitHub Desktop.
evaluates, copies, flatten, and renames my sample files
import os
import shutil
import re
def sanitize_filename(filename):
"""
Sanitizes the filename to ensure it contains only alphanumeric characters and underscores,
replacing any special characters with underscores. Preserves the file extension.
"""
# Separate the extension and the name
name, ext = os.path.splitext(filename)
# Replace non-alphanumeric characters (excluding the period for the extension) with underscores
sanitized_name = re.sub(r'[^0-9a-zA-Z.]+', '_', name)
return sanitized_name + ext
def flatten_and_rename(src_directory, target_directory):
# Ensure target directory exists
if not os.path.exists(target_directory):
os.makedirs(target_directory)
# Walk through all directories and files in the source directory
for root, dirs, files in os.walk(src_directory):
for file in files:
# Construct the original full file path
original_path = os.path.join(root, file)
# Generate the new file name by replacing directory separators with underscores
new_file_name = original_path.replace(src_directory, "").replace(os.sep, "_")[1:]
if any(ext in new_file_name for ext in [".mp3", ".wav", ".aif"]):
new_file_name = sanitize_filename(new_file_name)
# Construct the full path for the new file location
new_file_path = os.path.join(target_directory, new_file_name)
# Move and rename the file
shutil.copy(original_path, new_file_path)
print(f"Moved and renamed: {original_path} -> {new_file_path}")
# Example usage
src_directory = "./Samples"
target_directory = "./Samples_Flattened"
flatten_and_rename(src_directory, target_directory)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment