[Tutor] os.rename error problem

Jeff Shannon jeff at ccvcorp.com
Tue Nov 2 23:14:18 CET 2004


justin wrote:

>Hello,
>
>I know os.rename is pretty easy and straight forward to use but Im trippin up on
>something here.  In the interactive prompt I have no problem renaming a file.
>  
>

As others have suggested, check whether the source file is already open 
elsewhere in your program.  But I'm a bit puzzled about this segment:

>    for item in pathList:   # Adds the file names to the path
>        if os.path.isfile(item + '/' + old) == True:
>            old = item + '/' + old 
>            new = item + '/' + new 
>        else: pass
>  
>

It's not clear where your pathList is coming from (presumably it's a 
global variable, which (like all globals) is probably a poor design 
choice, but that's another story), but this is *not* an optimal way to 
build your paths.  Instead of manually adding together path elements 
with a character that you think should work as path separator, you 
should be using os.path.join() to assemble the elements.

An equivalent segment using os.path.join() might look like this:

    for item in pathList:
        if os.path.isfile(os.path.join(item, old)):
            old = os.path.join(item, old)
            new = os.path.join(item, new)

However, notice that if you've got more than one item in pathList, 
you're overwriting old and new on each iteration.  This is effectively 
equivalent to:

    if os.path.isfile(os.path.join(pathList[-1], old)):
        old = os.path.join(pathList[-1], old)
        new = os.path.join(pathList[-1], new)

Since we don't know what's in pathList, it's hard to say for certain 
whether this is a sensible thing to do or not, but my gut feeling is 
that you might want to reconsider how you're creating/using pathList.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Tutor mailing list