Skip to content Skip to sidebar Skip to footer

Replacing Filename Characters With Python

I have some code which adds the word '_manual' onto the end of a load of filenames.. I need to change the script so that it deletes the last two letters of the filename (ES) and t

Solution 1:

Try this:

import os
pathiter = (os.path.join(root, filename)
    for root, _, filenames in os.walk(folder)
    for filename in filenames
)
for path in pathiter:
    newname =  path.replace('ES.txt', '_ES_manual.txt')
    if newname != path:
        os.rename(path,newname)

Solution 2:

For a more generalized take on hughdbrown's answer. This code can be used to remove any particular character or set of characters.

import os

paths = (os.path.join(root, filename)
        for root, _, filenames in os.walk('C:\FolderName')
        for filename in filenames)

for path in paths:
    # the '#' in the example below will be replaced by the '-' in the filenames in the directory
    newname = path.replace('#', '-')
    if newname != path:
        os.rename(path, newname)

Solution 3:

for root, dirs, filenames in os.walk(folder):
    to_write = ['root == %s\n' % root]

    for filename in filenames:
        filename_zero, fileext = os.path.splitext(filename)
        newname = "%s_%s_manual%s" % (filename_zero[:-2],filename_zero[-2:],fileext)

        tu = (os.path.join(root, filename), os.path.join(root, newname))

        to_write.append('%s --> %s\n' % tu)
        os.rename(*tu)

    print '\n'.join(to_write)

Solution 4:

you could do:

for filename in filenames:
    print(filename) #should display AC-5400ES.txt
    filename = filename.replace("ES.txt","ES_manual.txt")
    print(filename) #should display AC-5400ES_manual.txt
    fullpath = os.path.join(root, filename)
    os.rename(fullpath, filename)

Solution 5:

Here is another alternative without using os.path.join or os.walk:

import os

fileLocation = "C:\\Documents and Settings\\DuffA\\Bureaublad\\test\\"
fileList = os.listdir(fileLocation)

for ii in fileList:
    newName = ii.replace('ES','_ES_Manual')
    if newName != ii:
        os.rename(fileLocation+ii,fileLocation+newName)

Post a Comment for "Replacing Filename Characters With Python"