StringTheory
StringTheory

Reputation: 11

How to add a random number for each file in a directory? (Beginner)

I have 10 images in a file and I want to rename them with a random number between 10 and 99 added to its existing file name.

For example:

FileA.jpg > 45FileA.jpg

FileB.jpg > 22FileB.jpg

The following is incorrect. How do I turn the random integers into strings within this function?

def random_rename():

    file_list = os.listdir(r"C:\Users\Directory\Desktop\prank\My_Message")

    for file_name in file_list: 
        os.rename(file_name, str(random.randint(10,99)) + file_name)

Upvotes: 1

Views: 683

Answers (1)

Jack
Jack

Reputation: 21163

As a commenter mentioned os.listdir does not return absolute paths so you need to join them with your actual path.

Try:

def random_rename():
    path = r"C:\Users\Directory\Desktop\prank\My_Message"
    file_list = os.listdir(path)
    for file_name in file_list: 
        old_name = os.path.join(path, file_name)
        new_name = os.path.join(path, str(random.randint(10,99)) + file_name)
        os.rename(old_name, new_name)

Upvotes: 3

Related Questions