Python rename special characters in filename

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

#!/usr/bin/env python

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('D:\OneDrive - T-Mobile Polska S.A')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    # 
    # 

    newname = path.replace('#', '-')
    newname = path.replace('%', '-')
    newname = path.replace('&', '-')
    newname = path.replace('*', '-')
    newname = path.replace('{', '-')
    newname = path.replace('}', '-')
    newname = path.replace('<', '-')
    newname = path.replace('>', '-')
    newname = path.replace('*', '-')
    newname = path.replace('?', '-')
    newname = path.replace('$', '-')
    newname = path.replace('!', '-')
    newname = path.replace('\'', '-')
    newname = path.replace('"', '-')
    

    if newname != path:
        #os.rename(path, newname)
        print('rename ----> ' + path + ' ' +  newname)
    # else:
    	#print(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 ↑