0

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!!!

Community
  • 1
  • 1
user2988464
  • 3,251
  • 6
  • 21
  • 25

3 Answers3

1

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)
smeso
  • 4,165
  • 18
  • 27
1

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)
greg
  • 1,417
  • 9
  • 28
0

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)
benwad
  • 6,414
  • 10
  • 59
  • 93