Rafał
Rafał

Reputation: 53

Replace dots in filename Python

im trying to replace all dots (and accents, but's already done) in filename with underscore except extension dot of course. I saw a lot of solutions but mainly with bash. Cant find for python. Probably I should use regex but dont have much experience here. Below my code:

path2 = 'xx'
dicto = {"ą":"a", 
         "ś":"s",
         "ę":"e",
         "ć":"c",
         "ż":"z",
         "ź":"z",
         "ó":"o",
         "ł":"l",
         "ń":"n"}

def find_replace(string, dictionary):
    for item in string:
        if item in dictionary.keys():
            string = string.replace(item, dictionary[item])
    return string

def change_name(path=path2):
    for root, dirs, files in os.walk(path):
        for filename in files:
            if not filename.startswith('~'):
                os.rename(os.path.join(root,filename), os.path.join(root,find_replace(filename, dicto)))


change_name()

Upvotes: 0

Views: 1713

Answers (3)

Joan Lara
Joan Lara

Reputation: 1396

Just use Unidecode

import unidecode

print(unidecode.unidecode('ąśęćżźółń))

Output:

aseczzoln

Upvotes: 1

benwiggy
benwiggy

Reputation: 2729

There are a number of existing answers here to remove diacritics from Unicode text in python. There is a unidecode library for python3 which does exactly what you need.

Removing diacritical marks using Python

What is the best way to remove accents in a Python unicode string?

Upvotes: 1

haemka
haemka

Reputation: 130

Check out os.path.splitext and replace dots only in the first part of the filename.

Upvotes: 0

Related Questions