Python rename special characters in filename

Problem

 

When upload files to One Drive i have problem with files contain special characters. Below you found Python script witch remove any special characters form filenames. Change

 

lv_path = "D:Netbeans Projects"

 

and enjoy!

 

Solution

 

#!/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)) +
              "ttt -> " + os.path.basename(newname.encode('utf8').decode(sys.stdout.encoding)))
        os.rename(path, newname)

 

Source(s)

 

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments