'Remove special character from multiple file names in folder in python
I am trying to remove special character(-) from multiple files in folder.
Example:
Filenames :
- -name1.xml
- -name2.xml
- -name3.xml
Rename To:
- name1.xml
- name2.xml
- name3.xml
My Code :
import os
for filename in os.listdir(Folder):
os.rename(Folder+'/'+filename, Folder + '/' + Filename.replace("-","" )
but Unfortunately it appears to do nothing.
How do I do this properly?
Solution 1:[1]
In the code below, you can simply use the replace function to get your desired output. Let me know if this works and/or helps!
import os
# I named my folder containing .XML files "Test"
Folder = 'Test/'
for filename in os.listdir(Folder):
os.rename(Folder + filename, Folder + filename.replace('-',''))
Outputs:
name1.xml
name2.xml
name3.xml
Solution 2:[2]
I am a big fan of using Pathlib for problems like this.
Given (on Unix but should work on all OSs):
% ls -1
-name1.xml
-name2.xml
-name3.xml
name-4.xml
You can do:
from pathlib import Path
p=Path(Folder)
for fn in p.glob("-*.xml"):
fn.replace(fn.with_name(str(fn.name).replace('-','')))
Result:
% ls -1
name-4.xml
name1.xml
name2.xml
name3.xml
The glob -*.xml only will find files that start with - so the file name-4.xml is unchanged.
Pathlib (as written here) will also work the same regardless of the path separator on different OSs.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
