'How to remove dots from a filename without removing them from the extension?

I am iterating through a folder that has files of different extensions. I want to remove dots ('.') from the filename, but not the extension. If I simply do this:

def filename_replacer(file_name):
    extension = file_name[-4:]
    raw_name = file_name[:-4]       
    new_name = raw_name.replace(".", "_")
    new_name = new_name + extension
    return new_name

file = "Remove.TheDotReport.xlsx"
cleaned_file = filename_replacer(file)

It comes out incorrect (ex: Remove_TheDotReport_xlxs). How can I consistently remove the dots in the file without messing up the extension?



Solution 1:[1]

Use os.path.splitext to get the extension out first.

import os

def filename_replacer(filename):
  fname, fext = os.path.splitext(filename)
  return fname.replace(".", "_") + fext

Solution 2:[2]

Since Python 3.4, a convenient way for working with paths is the pathlib built-in library. It treats paths as objects instead of simple strings.

Since Python 3.9, a new method was added - with_stem - which only changes the name of the file without the extension. So this can be done quite easily:

from pathlib import Path

path = Path("Remove.TheDotReport.xlsx")
print(path.with_stem(path.stem.replace('.', '_')))
# Remove_TheDotReport.xlsx

For older versions, you can still use the with_name method with a bit more work (adding the extension separately):

from pathlib import Path

path = Path("Remove.TheDotReport.xlsx")
print(path.with_name(path.stem.replace('.', '_') + path.suffix))
# Remove_TheDotReport.xlsx

Solution 3:[3]

This is for a bash script to remove dots from the filename and keep the extension dot if you want to change for anyone file ('dir /b *.filename') give filename here.

@echo off
for /f "delims=" %%a in ('dir /b *') do call :dot "%%a"
pause
goto :EOF
:dot
set "var=%~n1"
set "var=%var:.= %"
ren %1 "%var%%~x1"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Armin Primadi
Solution 2
Solution 3 Martijn Pieters