0

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

phenderbender
  • 625
  • 2
  • 8
  • 18
  • 1
    What have you tried so far? – zamir Jan 14 '20 at 19:56
  • I think this should bring you on the right foot: https://stackoverflow.com/questions/28614999/python-truncate-unknown-file-names – MSD Jan 14 '20 at 19:57
  • try using: https://docs.python.org/3/library/os.html#os.rename – YOLO Jan 14 '20 at 19:57
  • Try `man find`, look for `-exec`; you don't need to write your own program for this. – 9000 Jan 14 '20 at 19:57
  • In the shell, you need something like `mv "$dir" "${dir%_STAGE copy}"` for a single directory. Use `find ... -exec` to apply that to all relevant directories. – Sven Marnach Jan 14 '20 at 20:04

2 Answers2

1

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])
phenderbender
  • 625
  • 2
  • 8
  • 18
AmirHmZ
  • 516
  • 3
  • 22
  • thanks I'm getting close with this - this seems to work for files that end in `_STAGE COPY` but not folder names themselves – phenderbender Jan 14 '20 at 20:20
  • 1
    you wanna change directory names which end in `_STAGE COPY` too ? – AmirHmZ Jan 14 '20 at 20:21
  • Only folder names, no files. Within a folder I have many folders that all end in `_STAGE copy`, which I would like to remove from the folder names. I don't want to edit any of the actual files within those folders. – phenderbender Jan 14 '20 at 20:24
  • 1
    changed my answer, check it again @phenderbender – AmirHmZ Jan 14 '20 at 20:28
  • still doesn't seem to want to work. I'm trying to print 'folders' to see what the issue may be and it doesn't look like anything is being appended to the list – phenderbender Jan 14 '20 at 20:31
  • edited your response which was able to get me close to the solution, thanks for the help – phenderbender Jan 15 '20 at 15:14
0

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])
phenderbender
  • 625
  • 2
  • 8
  • 18