Python Forum
Rename all files in a folder
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rename all files in a folder
#1
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?
Reply
#2
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")
Reply
#3
(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?
Reply
#4
Sorry Gribouillis. It's my lunch break and I'm bored.
Reply
#5
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!
Reply
#6
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.
Reply
#7
(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?
Reply
#8
@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!
Reply
#9
(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.
Reply
#10
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 566 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Rename files in a folder named using windows explorer hitoxman 3 756 Aug-02-2023, 04:08 PM
Last Post: deanhystad
  How to loop through all excel files and sheets in folder jadelola 1 4,523 Dec-01-2022, 06:12 PM
Last Post: deanhystad
  python gzip all files from a folder mg24 3 4,034 Oct-28-2022, 03:59 PM
Last Post: mg24
  delete all files and subdirectory from a main folder mg24 7 1,637 Oct-28-2022, 07:55 AM
Last Post: ibreeden
  Merge all json files in folder after filtering deneme2 10 2,373 Sep-18-2022, 10:32 AM
Last Post: deneme2
  Rename part of filename in multiple files atomxkai 7 7,377 Feb-18-2022, 10:03 PM
Last Post: atomxkai
  Compare filename with folder name and copy matching files into a particular folder shantanu97 2 4,509 Dec-18-2021, 09:32 PM
Last Post: Larz60+
  Rename Files based on XML file klturi421 3 2,209 Oct-22-2021, 07:37 PM
Last Post: klturi421
  pyspark creating temp files in /tmp folder aliyesami 1 5,026 Oct-16-2021, 05:15 PM
Last Post: aliyesami

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020