Search code examples
pythonrenaming

Renaming filenames using python


I need to simply add the word "_Manual" onto the end of all the files i have in a specific directory Here is the script i am using at the moment - i have no experience with python so this script is a frankenstine of other scripts i had lying around!

It doesn't give any error messages but it also doesnt work..

folder = "C:\Documents and Settings\DuffA\Bureaublad\test"

import os, glob

for root, dirs, filenames in os.walk(folder):
    for filename in filenames:
        filename_split = os.path.splitext(filename) # filename and extensionname (extension in [1])
        filename_zero = filename_split[0]
        os.rename(filename_zero, filename_zero + "_manual")

I am now using

folder = "C:\Documents and Settings\DuffA\Bureaublad\test"
import os # glob is unnecessary
for root, dirs, filenames in os.walk(folder):
    for filename in filenames:
        fullpath = os.path.join(root, filename)
        filename_split = os.path.splitext(fullpath) # filename and extensionname (extension in [1])
        filename_zero, fileext = filename_split
        print fullpath, filename_zero + "_manual" + fileext
        os.rename(fullpath, filename_zero + "_manual" + fileext)

but it still doesnt work.. it doesnt print anything and nothing gets changed in the folder!


Solution

  • I. e. it does nothing? Let's see:

    folder = "C:\Documents and Settings\DuffA\Bureaublad\test"
    
    import os # glob is unnecessary
    
    for root, dirs, filenames in os.walk(folder):
        for filename in filenames:
            fullpath = os.path.join(root, filename)
            filename_split = os.path.splitext(fullpath) # filename and extensionname (extension in [1])
            filename_zero, fileext = filename_split
            os.rename(fullpath, filename_zero + "_manual" + fileext)
    

    might do the trick, as you have to work with the full path. but I don't understand why there was no exception when the files could not be found...


    EDIT to put the change to a more prominent place:

    You as well seem to have your path wrong.

    Use

    folder = r"C:\Documents and Settings\DuffA\Bureaublad\test"
    

    to prevent that the \t is turned into a tab character.