Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing Filename characters with python

I have some code which adds the word "_manual" onto the end of a load of filenames.. I need to change the script so that it deletes the last two letters of the filename (ES) and then replaces it with _ES_Manual for example: AC-5400ES.txt --> AC-5400_ES_manual.txt

How would i incorporate that function into this code?

folder = r"C:/Documents and Settings/DuffA/Bureaublad/test"
import os # glob is unnecessary
for root, dirs, filenames in os.walk(folder):
    for filename in filenames:
        fullpath = os.path.join(root, filename)
        filename_split = os.path.splitext(fullpath) # filename and extensionname (extension in [1])
        filename_zero, fileext = filename_split
        print fullpath, filename_zero + "_manual" + fileext
        os.rename(fullpath, filename_zero + "_manual" + fileext)
like image 778
Alice Duff Avatar asked Aug 23 '11 12:08

Alice Duff


1 Answers

Try this:

import os
pathiter = (os.path.join(root, filename)
    for root, _, filenames in os.walk(folder)
    for filename in filenames
)
for path in pathiter:
    newname =  path.replace('ES.txt', '_ES_manual.txt')
    if newname != path:
        os.rename(path,newname)
like image 94
hughdbrown Avatar answered Sep 17 '22 14:09

hughdbrown