wilbev
wilbev

Reputation: 5991

Renaming file in same directory using Python

So I'm trying to iterate through a list of files that are within a subfolder named eachjpgfile and change the file from doc to the subfolder eachjpgfile mantaining the file's name but when I do this it adds the file to directory before eachjpgfile rather than keeping it in it. Looking at the code below, can you see why is it doing this and how can I keep it in the eachjpgfile directory?

Here is the code:

for eachjpgfile in filelist:
    os.chdir(eachjpgfile)
    newdirectorypath = os.curdir
    list_of_files = os.listdir(newdirectorypath)
    for eachfile in list_of_files:
         onlyfilename = os.path.splitext(eachfile)[0]
         if onlyfilename == 'doc':
            newjpgfilename = eachfile.replace(onlyfilename,eachjpgfile)
            os.rename(eachfile, newjpgfilename)

Upvotes: 0

Views: 1194

Answers (2)

Queequeg
Queequeg

Reputation: 108

There is a lot of weird stuff going on in here, but I think the one that's causing your particular issue is using 'eachjpgfile' in 'eachfile.replace'.
From what I can tell, the 'eachjpgfile' you're passing in is a full-path, so you're replacing 'doc' in the filename with '/full/path/to/eachjpgfile', which puts it parallel to the 'eachjpgfile' directory regardless of your current working directory.

You could add a line to split the path/file names prior to the replace:

for eachjpgfile in filelist:
    os.chdir(eachjpgfile)
    newdirectorypath = os.curdir
    list_of_files = os.listdir(newdirectorypath)
    for eachfile in list_of_files:
         onlyfilename = os.path.splitext(eachfile)[0]
         if onlyfilename == 'doc':
            root, pathName= os.path.split(eachjpgfile) #split out dir name
            newjpgfilename = eachfile.replace(onlyfilename,pathName)
            os.rename(eachfile, newjpgfilename)

which is a very dirty fix for a very dirty script. :)

Upvotes: 1

lenik
lenik

Reputation: 23556

try this:

import os

path = '.'
recursive = False   # do not descent into subdirs

for root,dirs,files in os.walk( path ) :
    for name in files :
        new_name = name.replace( 'aaa', 'bbb' )

        if name != new_name :
            print name, "->", new_name
            os.rename( os.path.join( root, name),
                   os.path.join( root, new_name ) )

    if not recursive :
        break

Upvotes: 1

Related Questions