Introduction :
In this python programming tutorial, we will learn how to remove special characters from all files in a folder. We will remove the numeric digits, special characters and blank spaces from the files. Following are the steps we are going to use in the program :
-
Read all files one by one in the folder.
-
Check for each file if the name contains any special character,numeric value or blank space.
-
If it does, remove these characters from the file name.
To solve this problem, you need to know :
-
How to iterate through files in a folder in python.
-
How to modify a string in python and
-
How to rename a file.
If you already know how the above functionalities work, then it will not take much time to grab the main program below.
Python program :
First of all, create one directory and put a few files in it. We have created one directory named Sample inside the C drive with the below files :
first23@file
second_file
third file
Now, run the below python program :
#1
import os
from os import listdir
from os import path
#2
folder_path = 'C:\Sample\'
#3
def getModifiedPath(originalPath):
return ''.join(c for c in originalPath if c.isalpha())
#4
for filename in listdir(folder_path):
src = folder_path + filename
dst = folder_path + getModifiedPath(filename)
#5
os.rename(src,dst)
It will rename all files in the Sample folder as below :
firstfile
secondfile
thirdfile
As you can see that the file names are changed in the folder. All special characters, numbers and spaces are removed from the files.
Explanation :
The commented numbers in the above program denote the step numbers below :
-
Import os module and also import listdir and path from the os module.
-
folder_path is the path of the folder where all files are stored.
-
getModifiedPath function is used to remove all characters except alphabets from a string. It takes one string as a parameter and returns the modified string.
-
Use one for loop to iterate through the files stored in the folder one by one. listdir is used to list all files in a folder. src is the complete path of the source file we want to change and dst is the modified complete path for that file.
-
Finally, use rename() method to rename the source file src.
Conclusion :
I hope that you have found this tutorial helpful. Try to run the program and drop one comment below if you have any queries.