python-3.x - Renaming files in same directory with Python - TagMerge
2Renaming files in same directory with PythonRenaming files in same directory with Python

Renaming files in same directory with Python

Asked 10 months ago
0
2 answers

I eventually found a workaround though it may be clunky. Since renaming each file to a name used by a previous file is potentially causing the issue. I have decided to append an 'x' to the front of the files which are renamed with the same name as a file already present as below:

shutil.move(os.path.join(spamFolder, filename), os.path.join(spamFolder, 'x'+FileList[Counter1]))

I then simply us the os.walk feature to lstrip off the 'x'

Source: link

0

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

Source: link

Recent Questions on python-3.x

    Programming Languages