[Python] How to prevent [WinError 3] using shutil.move on .mp3 files whose artist tags contain...

Discussão em 'Python' iniciado por Stack, Agosto 18, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a Python script that:

    1. Notes all files in the working directory
    2. Reads the artist tag with the mutagen library
    3. Uses regex to grab the first-mentioned artist as the 'main artist'
    4. Creates a unique directory for that artist
    5. Uses shutil to move the .mp3 to that directory

    This works for most files, but I've noticed it gets a WinError 3 on any .mp3 whose mutagen artist tag contains ampersand or open-parenthesis. I've confirmed this by changing the tag and it gets moved without error.

    This is particularly odd because nowhere in the file paths do I reference the artist tag directly. It's picked up and run through a regex to make sure it's a standardized upper-cased string fit for a file path name in Windows.

    import mutagen
    import os
    import re
    import shutil

    current_dir = os.getcwd()
    files = [f for f in os.listdir('.') if os.path.isfile(f)]

    # for each file in the dir
    for f in files:
    #grab the artist (use first listed artist in the case of colabs) as a new directory name or UKNOWN if not listed
    try:
    audio = mutagen.File(f, easy=True)
    if audio is not None and "artist" in audio:
    artist = re.split(r";|,|&|\(|\/|\sfeat\.|\sFeat\.|\sft|\sFt|\sx\s",audio['artist'][0])[0].upper()
    else:
    artist = "UNKNOWN"
    except Exception as e:
    artist = "UNKNOWN"

    artist_path = os.path.join(current_dir,artist)
    item_path = os.path.join(current_dir,f)

    #make sure all the artist paths are unique
    os.makedirs(artist,exist_ok=True)

    #don't move the actual python script...
    if item_path[-2:] != 'py':
    try:
    shutil.move(item_path, artist_path)
    print("moved ",item_path," to ",artist_path)
    except Exception as e:
    print("Error on: ",f," -> ",e)
    print(item_path, os.path.exists(item_path))
    print(artist_path, os.path.exists(artist_path))


    Why would the metadata tag matter in this case?

    Continue reading...

Compartilhe esta Página