Reputation: 33
Whats best method to remove special charters (multiple characters) from file name currently I am doing this way but its not efficient to remove multiple different characters at same time eg %$^&* etc
import os
"""
Remove () and empty space from file names
"""
path = '/var/www/POD/2021/09/12'
os.chdir(path)
files = os.listdir(path)
for root, dirs, files in os.walk(path):
for f in files:
cwd = os.path.join(root, f[:0])
cwd = os.chdir(cwd)
os.rename(f, f.replace(' ', ''))
Upvotes: 0
Views: 482
Reputation: 33
Thanks this is how I manage to implement
path = 'C:\\Users\\User\\Desktop\\Test'
os.chdir(path)
remove = "( )"
for filename in os.listdir(path):
t = str.maketrans("", "", remove)
newname = filename.translate(t)
os.rename(filename, newname)
Upvotes: 0
Reputation: 36540
This look like task for .translate
method, consider following example
name = "name (with )brackets"
remove = "( )"
t = str.maketrans("", "", remove)
new_name = name.translate(t)
print(new_name)
output
namewithbrackets
Explanation: .maketrans
takes 2 or 3 arguments, first 2 must be equal-length str
s, n-th character from first is replace with corresponding character from second. I do not use this features, so I put empty str
, third argument is str with characters to remove.
Upvotes: 1