user2988464
user2988464

Reputation: 3461

rename filenames with index

i want to rename all the files in a folder. Each filename will change from "whateverName.whateverExt" to "namepre+i.whateverExt". e.g. from "xxxxx.jpg" to "namepre1.jpg"

i try the modify code from (Rename files in sub directories), but fail...

import os

target_dir = "/Users/usename/dirctectory/"

for path, dirs, files in os.walk(target_dir):
    for i in range(len(files)):
        filename, ext = os.path.splitext(files[i])
        newname_pre = 'newname_pre'
        new_file = newname_pre + str(i) + ext

        old_filepath = os.path.join(path, file)
        new_filepath = os.path.join(path, new_file)
        os.rename(old_filepath, new_filepath)

Can someone help me? THX!!!

Upvotes: 0

Views: 202

Answers (3)

smeso
smeso

Reputation: 4295

Probably you made some mistakes naming some variables, try with this:

import os

target_dir = "/Users/usename/dirctectory/"
newname_tmpl = 'newname_pre{0}{1}'

for path, dirs, files in os.walk(target_dir):
    for i, file in enumerate(files):
        filename, ext = os.path.splitext(file)
        new_file = newname_tmpl.format(i, ext)
        old_filepath = os.path.join(path, file)
        new_filepath = os.path.join(path, new_file)
        os.rename(old_filepath, new_filepath)

Upvotes: 1

greg
greg

Reputation: 1416

Try this version:

import os

target_dir = "/Users/usename/dirctectory/"

for path, dirs, files in os.walk(target_dir):
    for i in range(len(files)):
        filename, ext = os.path.splitext(files[i])
        newname_pre = 'newname_pre'
        new_file = newname_pre + str(i) + ext

        old_filepath = os.path.join(path, files[i]) # here was the problem
        new_filepath = os.path.join(path, new_file)
        os.rename(old_filepath, new_filepath)

Upvotes: 1

benwad
benwad

Reputation: 6594

You should probably update this question saying what output you get when you run this. Also, try printing out the value of new_file each iteration to see if you're getting a correct filepath. My guess is that this line:

new_file = newname_pre + str(i) + ext

...should say this:

new_file = newname_pre + str(i) + '.' + ext

...or, in a slightly more Pythonic syntax:

new_file = "%s%i.%s" % (newname_pre, i, ext)

Upvotes: 0

Related Questions