Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing characters from filename in batch

I have 3 main folder in Windows explorer that contain files with naming like this ALB_01_00000_intsect_d.kml or Baxters_Creek_AL_intsect_d.kml. Even though the first name changes the consistent thing that I would like to remove from all these files is "_intsect_d". Would like to do this for all files within each of the folders. The files have an extension .kml. The result I am expecting as per the example above is ALB_01_00000.kml and the other one would be Baxters_Creek_AL.kml. Dont know much about programming in python, but would like help to write a script that can acheive the result mentioned above. Thanks

like image 469
user3754653 Avatar asked Jun 19 '14 01:06

user3754653


2 Answers

This code can be used to remove any particular character or set of characters recursively from all filenames within a directory and replace them with any other character, set of characters or no character.

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('C:\FolderName')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('#', '-')
    if newname != path:
        os.rename(path, newname)
like image 36
nicholas Avatar answered Oct 19 '22 02:10

nicholas


import os
for filename in os.listdir('dirname'):
    os.rename(filename, filename.replace('_intsect_d', ''))
like image 162
Aesthete Avatar answered Oct 19 '22 02:10

Aesthete