rename filenames from uppercase to lowercase

Viewed 4087

I want to rename all upper case letters from file names to lower case letters.

my file structure

p:\TeSt\001-Movie.txt
p:\TeSt\002-moVie.txt
p:\TeSt\003-Pics.txt
p:\TeSt\004-KKKFLfasf.txt

and this is how it should look

p:\TeSt\001-movie.txt
p:\TeSt\002-movie.txt
p:\TeSt\003-pics.txt
p:\TeSt\004-kkkflfasf.txt

However, the folder should not be renamed

import os
path = 'p:\TeSt'
for file in os.listdir():
    os.rename(file, file.lower())
then = os.listdir()

but I get an error and the files are not renamed.

1 Answers

You just need to give the full path of the files and pass that to the rename function, it should work.

Try the below code:

import os

path = 'p:/TeSt/'

for file in os.listdir(path):
    os.rename(path + file, path + file.lower())

then = os.listdir(path)
print(then)

output:

['001-movie.txt', '004-kkkflfasf.txt', '002-movie.txt', '003-pics.txt']

NOTE: Forwadslash (/) has been used in order to avoid using (\) which is a special character in python. You can always replace / with \\ in windows.

Related