Introduction:
Managing and organizing a music collection often involves keeping track of the artist and song information associated with each MP3 file. Manually updating ID3 tags can be a time-consuming task, especially when dealing with a large number of files. However, with the power of Python and the Mutagen library, we can automate this process and save valuable time. In this article, we will explore a Python script that updates ID3 tags for MP3 files based on the filename structure.
Prerequisites:
To follow along with this tutorial, make sure you have Python and the Mutagen library installed on your system. You can install Mutagen by running pip install mutagen in your terminal.
Understanding the Code:
The Python script we’ll be using leverages the Mutagen library to handle ID3 tag manipulation. The core logic resides in the update_id3_tags function, which updates the ID3 tags of an MP3 file based on the filename structure.
The script accepts command-line arguments using the argparse module, allowing you to specify the folder containing your MP3 files, along with options to ignore files with existing ID3 tags and print verbose output. This provides flexibility and customization to suit your specific requirements.
The getargs function parses the command-line arguments and returns the parsed arguments as an object. The folder_path, ignore_existing, and verbose variables are then extracted from the parsed arguments.
The script retrieves a list of MP3 files in the specified folder and iterates over each file. For each file, the update_id3_tags function is called. It extracts the artist and song name from the filename using the specified structure. The ID3 tags are then updated with the extracted information using the Mutagen library.
Code:
#!/usr/bin/env python
import os
import argparse
from mutagen.id3 import ID3, TIT2, TPE1
def update_id3_tags(filename, ignore_existing, verbose):
# Extract artist and song name from filename
basename = os.path.basename(filename)
print(f"processing --[{basename}]--")
if "-" in basename:
artist = basename[:-4].split(" - ")[0].strip()
song = " - ".join(basename[:-4].split(" - ")[1:]).strip()
else:
print("Cannot split file not in format [artist] - [song].mp3")
return -1
# Load the ID3 tags from the file
audio = ID3(filename)
# Check if ID3 tags already exist
if not ignore_existing or not audio.tags:
# Update the TIT2 (song title) and TPE1 (artist) tags if they are empty
if not audio.get("TIT2"):
audio["TIT2"] = TIT2(encoding=3, text=song)
if verbose:
print(f"Updated TIT2 tag for file: {filename} with value: {song}")
elif verbose:
print(f"Skipping existing ID3 tag for title: {audio.get('TIT2')}")
if not audio.get("TPE1"):
audio["TPE1"] = TPE1(encoding=3, text=artist)
if verbose:
print(f"Updated TPE1 tag for file: {filename} with value: {artist}")
elif verbose:
print(f"Skipping existing ID3 tag for track: {audio.get('TPE1')}")
print('-'*10)
# Save the updated ID3 tags back to the file
audio.save()
def getargs():
# parse command-line arguments using argparse()
parser = argparse.ArgumentParser(description='Update ID3 tags for MP3 files.')
parser.add_argument("folder", nargs='?', default='.', help="Folder containing MP3 files (default: current directory)")
parser.add_argument('-i', "--ignore", action="store_true", help="Ignore files with existing ID3 tags")
parser.add_argument('-v', "--verbose", action="store_true", help="Print verbose output")
return parser.parse_args()
if __name__ == '__main__':
args = getargs()
folder_path = args.folder
ignore_existing = args.ignore
verbose = args.verbose
# Get a list of MP3 files in the folder
mp3_files = [file for file in os.listdir(folder_path) if file.endswith(".mp3")]
# Process each MP3 file
for mp3_file in mp3_files:
mp3_path = os.path.join(folder_path, mp3_file)
update_id3_tags(mp3_path, ignore_existing, verbose)
Example:
Let’s assume you have a folder called “Music” that contains several MP3 files with filenames in the format “artist – song.mp3”. We want to update the ID3 tags for these files based on the filename structure.
Here’s how you can use the Python script:
python script.py Music --ignore --verbose
In this example, we’re running the script with the following arguments:
Music: The folder containing the MP3 files. Replace this with the actual path to your folder.--ignore: This flag tells the script to ignore files that already have existing ID3 tags.--verbose: This flag enables verbose output, providing details about the files being processed and the updates made.
By running the script with these arguments, it will update the ID3 tags for the MP3 files in the “Music” folder, ignoring files that already have existing ID3 tags, and provide verbose output to the console.
Once the script finishes running, you can check the updated ID3 tags using any media player or music library software that displays the ID3 tag information.
This example demonstrates how the Python script automates the process of updating MP3 ID3 tags based on the filename structure, making it convenient and efficient to manage your music collection.
Conclusion:
Automating the process of updating MP3 ID3 tags can save you valuable time and effort. With the Python script we’ve discussed in this article, you can easily update the ID3 tags of your MP3 files based on the filename structure. The flexibility offered by command-line arguments allows you to tailor the script to your specific needs. Give it a try and simplify your music collection management!




