Python Forum

Full Version: Rename all files in a folder
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone,

I have a folder which contains all files exported from Dropbox. All these files have been named using the date when they are created. The names have the format as: YYYY-MM-DD HH.MM.SS. For example, 2023-05-31 15.29.51.

I just want to rename they as: YYYY_MM_DD. If there are multiple files with the same date, then just make it as: YYYY_MM_DD (1), YYYY_MM_DD (2), ...

Do you know how I can use a smart Python code to automate this task?
from pathlib import Path
import re

pattern = re.compile(r"(\d{4}-\d{2}-\d{2}) \d{2}\.\d{2}\.\d{2}")


def rename_file(file, new_name):
    """Rename file named YYYY-MM-DD HH.MM.SS.ext to  YYY-MM-DD (V).ext"""
    suffix = file.suffix
    new_name = str(file.parent / new_name)  # Append new file name to path
    version = 0
    while True:
        # Try to rename file.  May need to append version number.
        try:
            if version > 0:
                file.rename(f"{new_name} ({version}){suffix}")
            else:
                file.rename(f"{new_name}{suffix}")
            break
        except FileExistsError:
            version += 1


def rename_files_in_folder(folder_name):
    """Rename files in folder named YYYY-MM-DD HH.MM.SS.ext to  YYY-MM-DD (V).ext"""
    for file in Path(folder_name).iterdir():
        match = re.match(pattern, file.stem)  # Match just the name part.
        if match:
            rename_file(file, match.group(1))


rename_files_in_folder("some folder name")
(Jun-28-2023, 01:47 PM)hitoxman Wrote: [ -> ]Do you know how I can use a smart Python code to automate this task?
Sure we know, we could also help you with your code, but if there is no code, then perhaps you could find a freelancer in the Jobs subforum. Do you want me to move the thread to this subforum?
Sorry Gribouillis. It's my lunch break and I'm bored.
Why not keep the whole name, just put an underscore where the space is? Less bother than renaming and numbering

I had some .wma audio files with spaces, I wanted to convert them to .mp3 using ffmpeg. But first I had to get rid of the spaces in the names first, bash doesn't like spaces.

This one-liner bash script removes all spaces and puts an underscore:

Quote:find . -type f -name "* *.*" -exec bash -c 'mv -v "$0" "${0// /_}"' {} \;

Not Python, but very effective!
The space is not a problem. Notice that the desired file names also contain a space. The OP does not like the timestamp for some reason.
(Jun-28-2023, 03:16 PM)deanhystad Wrote: [ -> ]
from pathlib import Path
import re

pattern = re.compile(r"(\d{4}-\d{2}-\d{2}) \d{2}\.\d{2}\.\d{2}")


def rename_file(file, new_name):
    """Rename file named YYYY-MM-DD HH.MM.SS.ext to  YYY-MM-DD (V).ext"""
    suffix = file.suffix
    new_name = str(file.parent / new_name)  # Append new file name to path
    version = 0
    while True:
        # Try to rename file.  May need to append version number.
        try:
            if version > 0:
                file.rename(f"{new_name} ({version}){suffix}")
            else:
                file.rename(f"{new_name}{suffix}")
            break
        except FileExistsError:
            version += 1


def rename_files_in_folder(folder_name):
    """Rename files in folder named YYYY-MM-DD HH.MM.SS.ext to  YYY-MM-DD (V).ext"""
    for file in Path(folder_name).iterdir():
        match = re.match(pattern, file.stem)  # Match just the name part.
        if match:
            rename_file(file, match.group(1))


rename_files_in_folder("some folder name")

Do you test it?
@deanhystad Oh, I understood the OP OK, just making a suggestion 1 line instead of 32.

Unless it is some homework or something, must be done exactly that way!
(Jun-29-2023, 05:06 AM)Pedroski55 Wrote: [ -> ]must be done exactly that way!
You could also try specialized tools such as rename. Renaming files in a directory is a recurring task.
Exactly!

When I was converting the .wma files to .mp3 I looked at many ways to get rid of the spaces in the names!

I installed rename.

Quote:find . -name "* *.wma" -type f | rename '\/ s/ /_/g'

Python is great and very useful, but sometimes bash script is better!