Python rename special characters in filename

Problem: when upload files to One Drive i have problem with files contain special characters. Find solution:

rename spec characters (Python 3+, W7)
#!/usr/bin/env python
#
# wychwytywanie i zmiana nazwy plików
#
import os
import string
import re
import sys

delchars = ''.join(c for c in map(chr, range(256)) if not c.isalnum())

# paths = (os.path.join(root, filename)
#          for root, _, filenames in os.walk('.')
#          for filename in filenames)

# print(paths)
lv_path = "D:\\Netbeans Projects"

paths = (os.path.join(root, filename)
         for root, _, filenames in os.walk(lv_path)
         for filename in filenames)

print ("Search at " + lv_path)

for path in paths:
    newname = path.replace('#', '')
    newname = newname.replace('%', '')
    newname = newname.replace('*', '')
    newname = newname.replace('<', '')
    newname = newname.replace('>', '')
    newname = newname.replace('*', '')
    newname = newname.replace('?', '')
    newname = newname.replace('$', '')
    #newname = newname.replace('!', '')
    #newname = path.replace('\'', '-')
    newname = newname.replace('"', '')
    newname = newname.replace('\'', '')
    newname = path.replace('Å', 'ś')
    newname = path.replace('Å', 'ń')
    #newname = path.translate(str.maketrans("","",delchars))

    #re.sub('[^\w\-_\. ]', '_', newname)

    if newname != path:
        # print(path)
        print(os.path.dirname(path.encode('utf8').decode(sys.stdout.encoding)) + "\t" + os.path.basename(path.encode('utf8').decode(sys.stdout.encoding)) +
              "\t\t\t -> " + os.path.basename(newname.encode('utf8').decode(sys.stdout.encoding)))
        os.rename(path, newname)

Sources:

  • http://www.mtu.edu/umc/services/digital/writing/characters-avoid/
  • https://stackoverflow.com/questions/2759067/rename-multiple-files-in-a-directory-in-python
  • https://ideone.com/RH1LrL
  • https://serverfault.com/questions/348482/how-to-remove-invalid-characters-from-filenames

Proudly powered by WordPress | Theme: Baskerville 2 by Anders Noren.

Up ↑