‘Tuple’ Object Has No Attribute ‘Replace’

I got the, ” ‘Tuple’ Object Has No Attribute ‘Replace’ ” error when trying to rename some file paths using python 2.x. This is because the os.walk(dst) returns an array of tuples. Accessing the first element in this tuple can solve the error. I was initially doing the following.

import os
for dir in os.walk('/Users/You/path/in/question'):
    newDir = dir.replace(oldWord, newWord)
    if newDir != dir:
        os.rename(dir, newDir)

dir in this case is the tuple the error is mentioning and replace can only be done to strings. We need to pull the string from the result of os.walk by tacking on a [0] to the tuple. The new script will look like the following.

import os
for dir in os.walk('/Users/You/path/in/question'):
    newDir = dir[0].replace(oldWord, newWord)
    if newDir != dir[0]:
        os.rename(dir[0], newDir)

This should no longer give you the ‘tuple’ object has no attribute ‘replace’ message, but I’m finding that there are grander issues with the organization of folder renaming. So, I still have work to do fortunately/unfortunately. Check out our editing images with Python article to learn another quick time saving hack! Cheers and happy coding!

Leave a Comment