jstnms123
jstnms123

Reputation: 19

python script executes in python interpreter, fails as .py file

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.

Upvotes: 1

Views: 30

Answers (1)

ottomeister
ottomeister

Reputation: 5828

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.

Upvotes: 1

Related Questions