How to change certain characters of files within a folder

Viewed 45

I have a folder named "animals"

Inside the folder I have the following files:

"cat.PNG", "dog.PNG", "horse.PNG", "sheep.PNG"

I know the following code will change the files to lowercase

files = os.listdir('.')
for f in files:
    new = f.lower()
    os.rename(f, new)

But how would I change this if I wanted the file type to be lower and the name of the animal to be upper of every file?

5 Answers

The cleanest way (which works for any directory and any extension too):

for f in os.listdir(source_dir):
    name,ext = os.path.splitext()    
    os.rename(os.path.join(source_dir,f), os.path.join(source_dir,name+ext.lower())
  • split name into radix+extension
  • convert extension to lowercase
  • perform rename with full path

A really simple solution would be the following:

for f in files:
    new = f.upper()
    new.replace(".PNG", ".png")
    os.rename(f, new)

You can split the file name, do each operation individually, then rejoin them.

files = os.listdir('.')
for f in files:
    # Split the filename by '.'
    split_filename = f.split('.')

    filename = ".".join(split_filename[:-1])
    extension = split_filename[:-1]

    # Do each operation
    filename = filename.upper()
    extension = extension.lower()

    # Rejoin the filename
    new_filename = filename + '.' + extension

    # Rename the file
    os.rename(new_filename, new)
(base, ext) = f.split('.')
new_name = f'{c.upper()}.{d.lower()}'
os.rename(f, new_name)

You can use split and join, see this example:

file_names = ["cat.PNG", "dog.PNG", "horse.PNG", "sheep.PNG"]

for file_name in file_names:
    name, extension = file_name.split('.')

    print('.'.join([name.upper(), extension.lower()]))
Related