0

I have this little script that changes characters from the beginning of filenames in the directory script is ran in. I would like to let the user input the directory to change files in. Im not sure how to implement that.

#!/usr/bin/env python3

import os

place = input("Enter the directory the files are in ")
drop  = input("Enter text to remove from filename ")
add   = input("Enter text to add to filename ")

for filename in os.listdir("."):
    if filename.startswith(drop):
        os.rename(filename, add+filename[len(drop):])
Anon_guy
  • 155
  • 10

1 Answers1

1

From the documentation:

os.listdir(path='.') Return a list containing the names of the entries in the directory given by path.

Hence just change "." to a string containing the path of the directory.

For example, from command-line, you can do:

mypath = input("Type path dir: ")
for filename in os.listdir(mypath):
    ...

mypath can be both absolute or relative path.

EDIT

I forgot to say: as mentioned also here os.rename() needs the full path of the file if they are in a different directory.

Something like this should work, if mypath is the full path:

os.rename(os.path.join(mypath, filename), os.path.join(mypath, add, filename[len(drop):]))

If not, you should build the full path.

thebard
  • 18
  • 1
Valentino
  • 7,291
  • 6
  • 18
  • 34
  • I tried that and I get this error. Its a subfolder Im trying this on I tried a fill and partial path to no avail. Traceback (most recent call last): File "./renamer.py", line 11, in os.rename(filename, add+filename[len(drop):]) FileNotFoundError: [Errno 2] No such file or directory: 'foo.bar' -> 'boo.bar' – Anon_guy Jan 17 '19 at 01:35