3

I am trying to rename a list of files with names for example: This is File 132 (file no 132) to This is File 132. So what I want is to replace (file no *) with ''. How to implement this *, where ultimately I want to replace this particular place in the name in every file. This is the code I have written so far. Any help is appreciated.

import os

directoryname = "/media/username/New Volume/"

listFiles = os.listdir(directoryname)
print(listFiles)
for i in listFiles:
    os.rename(os.path.join(directoryname, i), os.path.join(directoryname, i.replace('(file no 132)', '')))

listFiles = os.listdir(directoryname)
print(listFiles)
subtleseeker
  • 4,415
  • 5
  • 29
  • 41
  • 1
    `split`, `partition` or `re` are the answer here - replace can't do pattern matching. – match Jan 19 '18 at 11:47
  • 1
    The simplest (yet the ugliest) way is to drop the part that comes after 1 char before the `(` (assuming all files follow this pattern): `i[:i.find("(") - 1]` (where `i` is the old file name). – CristiFati Jan 19 '18 at 11:51
  • A quick test of performance puts as the fastest out of all of these (including the `find` method) (all splitting on `' (file no'`) – match Jan 19 '18 at 12:06
  • Thanks everyone! The solutions till now work fine. But as said in the question, I want to replace the 'changing number' in some way(one pretty way is like we use * in google search). The answers suggest cropping everything after the '(' which all removes the extension of the file too. Other way is to save the extension and join it after the cropping but there have to be some better way. – subtleseeker Jan 19 '18 at 12:33
  • Sorry, forgot about the extension: `os.path.splitext(i)[1]` – CristiFati Jan 19 '18 at 13:08

2 Answers2

1

Use one of split, partition or find (thanks to CristiFati for the suggestion) for this:

os.rename(os.path.join(directoryname, i), os.path.join(directoryname, i.split(' (file no')[0]))

os.rename(os.path.join(directoryname, i), os.path.join(directoryname, i.partition(' (file no')[0]))

os.rename(os.path.join(directoryname, i), os.path.join(directoryname, i[:i.find(' (file no') -1)])

In testing, partition is the fastest of the 3 (and re is much slower for this simple manipulation).

match
  • 10,388
  • 3
  • 23
  • 41
0

Just try this :

for i in listFiles:
     k = re.sub(r'\([^)]*\)', '', i)
     os.rename(os.path.join(directoryname, i), os.path.join(directoryname, k))

remaining all code keep same

Vikas Periyadath
  • 3,088
  • 1
  • 21
  • 33