I am writing the below code to remove the numerals and special characters if they appear at the starting of a file name. I have a working version of the code however i was trying few things and i noticed something which confused me.
Below is the code that works just fine.
import re
import os
DIR = 'C:\Rohit\Study\Python\Python_Programs\Basics\OOP'
os.chdir(DIR)
for file in os.listdir(DIR):
if os.path.isfile(os.path.join(DIR, file)):
fname, ext = os.path.splitext(file)
fname = re.sub(r'(^[0-9. _-]*)(?=[A-Za-z])', "", fname)
new_name = fname + ext
os.rename(file, new_name)
However if I simply remove the line os.chdir(DIR)
from above code, I start getting the below error.
FileNotFoundError: [WinError 2] The system cannot find the file specified: '6738903-. --__..76 test.py'
Below is the code that throws the error.
DIR_PATH = r'C:\Rohit\Study\Python\Python_Programs\Basics\OOP'
for file in os.listdir(DIR):
if os.path.isfile(os.path.join(DIR, file)):
fname, ext = os.path.splitext(file)
fname = re.sub(r'(^[0-9. _-]*)(?=[A-Za-z])', "", fname)
new_name = fname + ext
os.rename(file, new_name)
The error is getting generated on the line os.rename()
.
So can anyone please suggest what am I doing wrong here ?