1

I have been given data which cannot be interpreted by my software unless it has a lowercase letter at the end. The data was delivered with an uppercase letter at the end.

Somehow I need to first recursively loop through all folders and find whether the filename ends with a letter and then change it to lowercase.

I think python could do this, but I don´t know how,. Any help would be great!

yours, Rob

PeeHaa
  • 71,436
  • 58
  • 190
  • 262
Robert Buckley
  • 11,196
  • 6
  • 24
  • 25
  • 10
    I've seen very strange behaving software, but only being able to operate on files with names that end in a lower-case letter definitely might make it into the top ten. :) – Sven Marnach Nov 29 '11 at 17:25

2 Answers2

4
import fnmatch
import os

rootPath = '/'
pattern = '*.mp3'

for root, dirs, files in os.walk(rootPath):
    for filename in fnmatch.filter(files, pattern):
        os.rename(filename, filename[:-1] + filename[-1:].lower())

Sources: http://rosettacode.org/wiki/Walk_a_directory/Recursively#Python

Rename Files in Python

Community
  • 1
  • 1
bpgergo
  • 15,669
  • 5
  • 44
  • 68
  • 1
    `filename[-1]` instead of `filename[-1:]`, less confusing ;) – juliomalegria Nov 29 '11 at 17:40
  • Maybe using `*.mp3` as example pattern isn't the best choice if the aim is to change the last letter of the filename to lower case -- a lower case `3` will still be a `3`, so the code will do essentially nothing. – Sven Marnach Nov 29 '11 at 18:22
  • I think that a good addition to this answer would be to add `if filename[-1].isalpha():` then do the conversion. Just to be sure, that is. Wishing I could delete this now. It doesn't matter... – Vorticity Nov 29 '11 at 21:13
4
def listFiles(dir):
    rootdir = dir
    for root, subFolders, files in os.walk(rootdir):
        for file in files:
            yield os.path.join(root,file)
    return


for f in listFiles(r"Your Path"):
    if f[-1].isalpha():
        os.rename(f,f[:-1]+f[-1].lower())
        print "Renamed " + f + "to" + f[:-1]+f[-1].lower()

List the files recursively. If the last character is an alphabet change it to lowercase and rename the file


Modifying the program as per the poster's latest requirement

for fname in listFiles(r"Your Path"):
        newName=re.match("(^.*?)([A-Za-z\.]*$)",x)
        newName=''.join([newName[0],newName[1].lower()])
        os.rename(fname,newName)
        print "Renamed " + fname + "to" + newName
Abhijit
  • 62,056
  • 18
  • 131
  • 204