Reputation: 155
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):])
Upvotes: 0
Views: 43
Reputation: 7361
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.
Upvotes: 1