Python rename special characters in filename

Problem

When upload files to One Drive i have problem with files contain special characters.

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)

Source(s)

Comments are closed.

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

Up ↑