Using python with Windows Im trying to rename several files at once that are in the same folder but I cant use a list to do a rename that is why I get this error when I try my code:
os.rename(dirlist[1], words[1]) WindowsError: [Error 2] The system
cannot find the file specified
Here is the sample code:
import os
import sys
words = os.listdir('C:/Users/Any/Desktop/test')
dirlist = os.listdir('C:/Users/Any/Desktop/test')
words = [w.replace('E', 'e') for w in words]
print words
os.rename(dirlist[1], words[1])
What I am trying to achieve is have my python script ran on a folder of choice and the script will take all the files in there and will rename all of them. But the tricky part comes when I cant single out the folder names and have them renamed because they are attached to the list.
os.listdiris only giving you back the basename results. Not full path. They don’t exist in your current working directory. You would need to join them back with the root:Update
In response to your comment about how to perform larger number of replacements, I had suggested you could use
translateandmaketrans.Let’s start with our dict and a source string:
First, let me show you an example of a very primitive and entry level approach:
That example loops over your dictionary, calling the replacement multiple times. It works, and it makes perfect sense, using simple syntax. But it kind of sucks having to loop over the dictionary for every string and call replace multiple times.
There are many other ways to do this I am sure, but another approach is to create a translation table once, and then reuse it for every string:
That will split the dictionary out to key and value tuples. Then we join then intro strings and pass them to
maketrans, which will give us back a table. We only have to do that once. Now we have a table and can use it to translate any string.