1

my script:

from os import walk, path, rename

def rename(source, dest):
    for root, sub, files in walk(source):
        for file in files:
            if file.endswith('.mp4'):
                nbase = file.split('.mp4')[0]
                newname = nbase[0:len(nbase) - 12] + '.mp4'

                nsource = path.join(root, file)
                rdest = path.join(dest,newname)

                rename(nsource,rdest)

s = '/Users/ja/Desktop/t'
d = '/Users/ja/Desktop/u'

rename(s,d)

This script, line for line, will run in ipython, rename and relocate a file without issue. when scripted in sublimetext, or in textedit, and saved, it throws no errors, but does nothing. I am on macOS mojave.

2
  • have you tried a single "print" statement too? Commented Feb 21, 2019 at 20:53
  • Yes, I have tried. Again, total blank. Commented Feb 22, 2019 at 0:35

1 Answer 1

1

The problem is that you have given your function the name rename, but inside the function you're also trying to use the name rename to invoke os.rename. The result is that os.rename is never called. Instead your function makes a recursive call to itself with the old and new filenames as arguments.

That recursive call does nothing because walk(source) returns nothing when passed a filename. The end result is a program that walks the old directory tree correctly but never does anything to the files it finds in that tree.

To fix, give your function a different name that does not clash with os.rename. Maybe something like rename_in_tree. Alternatively, import os.rename with a name other than rename (from os import rename as os_rename) and call it through that new name from inside your function.

I've no idea how this happens to work in ipython. REPL handlers sometimes do strange things with naming scopes, but it seems bizarre that it would somehow call os.rename instead of making the recursive call to your function.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.