phenderbender
phenderbender

Reputation: 785

Remove a set string from many directories in Python

I have a folder /users/my/folder which contains many folders which all have names that end with _STAGE copy. I would like to remove the end of the folder name _STAGE copy and keep everything before it in the folder name.

I have found examples to provide the before/after name, but none that will remove a particular string in bulk from many folders within a directory.

This seems painfully simple but I'm having a hard time figuring it out

Upvotes: 0

Views: 83

Answers (2)

phenderbender
phenderbender

Reputation: 785

Still getting the hang of stack overflow, sorry for editing the previous response. Based on some of the replies and further reading I was able to resolve using this:

import os

path = '/directory/path/'
folders = []
for r, d, f in os.walk(path):
    for folder in d:
        folders.append(os.path.join(r, folder))
for f in folders:
    print(f)     

for f in folders:
    if f[-11:] == "_STAGE copy" :
        os.rename(f, f[:-11])

Upvotes: 0

AmirHmZ
AmirHmZ

Reputation: 556

Try it :

import os

path = "dir/"
folders = []
for r, d, f in os.walk(path):
for folder in d:
    folders.append(os.path.join(r, folder))

for f in folders:
    if f[-11:] == "_STAGE copy":
        os.rename(f, f[:-11])

Upvotes: 1

Related Questions