rename files with list of special characters in python
Question: What's an efficient way to remove a list of special characters from a
filename? I want to replace 'spaces' with '.' and '(', ')', '[',']' with '_'.
I can do it for one, but I'm not sure how to rename multiple characters.

    
    
    import os
    import sys
    files = os.listdir(os.getcwd())
    
    for f in files:
        os.rename(f, f.replace(' ', '.'))
    


Answer: You could do a for loop that checks each character in the file name and
replace:

    
    
    import os
    files = os.listdir(os.getcwd())
    under_score = ['(',')','[',']'] #Anything to be replaced with '_' put in this list.
    dot = [' '] #Anything to be replaced with '.' put in this list.
    
    for f in files:
        copy_f = f
        for char in copy_f:
            if (char in dot): copy_f = copy_f.replace(char, '.')
            if (char in under_score): copy_f = copy_f.replace(char,'_')
        os.rename(f,copy_f)
    

The trick with this is the second for loop runs **len(copy_f)** times which
will certainly replace all characters that match the criteria :) Also, there
was no need for this import:

    
    
    import sys
    

