0

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 ?

Rohit
  • 3,659
  • 3
  • 35
  • 57

1 Answers1

2

If file is not a valid path relative to the current directory (which is not the case if you don't do a chdir) you should provide rename with the full paths. Otherwise, how do you expect the function to find the file to rename? You did good using os.path.join in isfile why not doing that with rename?

DIR_PATH = r'C:\Rohit\Study\Python\Python_Programs\Basics\OOP'

for file in os.listdir(DIR):
    full_path = os.path.join(DIR, file)
    if os.path.isfile(full_path):
        fname, ext = os.path.splitext(file)
        fname = re.sub(r'(^[0-9. _-]*)(?=[A-Za-z])', "", fname)
        new_name = fname + ext
        os.rename(full_path, os.path.join(DIR, new_name))
Anis
  • 2,984
  • 17
  • 21
  • Thanks alot, my bad i simply didn't look at it, obviously os.rename(file, new_name) would find the file in current path. Sorry my bad. – Rohit Aug 25 '17 at 10:51
  • @Rohit also not that Anis uses raw prefixes for paths so he doesn't need to uppercase all letters after the backslash to workaround the "strange issue" :) – Jean-François Fabre Aug 25 '17 at 10:56
  • 2
    also note that chdir is bad practice: what if another module expects another current directory? that will be a chdir battle. Avoid at all costs. – Jean-François Fabre Aug 25 '17 at 10:57