Reputation: 43
I want to write a python program to rename all the files from a folder so that I remove the numbers from file name, for example: chicago65.jpg will be renamed as chicago.jpg.
Below is my code but I am getting error as translate() takes only 1 argument. please help in resolving this
import os
def rename_files():
file_list=os.listdir(r"C:\Users\manishreddy\Desktop\udacity\Secret Message\prank\prank")
print(file_list)
os.chdir(r"C:\Users\manishreddy\Desktop\udacity\Secret Message\prank\prank")
for file_temp in file_list:
os.rename(file_temp,file_temp.translate(None,"0123456789"))
rename_files()
Upvotes: 4
Views: 5030
Reputation: 405
If all you are looking to accomplish is to do the same thing you were doing in Python 2 in Python 3, here is what I was doing in Python 2.0 to throw away punctuation and numbers:
text = text.translate(None, string.punctuation)
text = text.translate(None, '1234567890')
Here is my Python 3.0 equivalent:
text = text.translate(str.maketrans('','',string.punctuation))
text = text.translate(str.maketrans('','','1234567890'))
Basically it says 'translate nothing to nothing' (first two parameters) and translate any punctuation or numbers to None (i.e. remove them).
Upvotes: 2
Reputation: 1122172
You are using the Python 2 str.translate()
signature in Python 3. There the method takes only 1 argument, a mapping from codepoints (integers) to a replacement or None
to delete that codepoint.
You can create a mapping with the str.maketrans()
static method instead:
os.rename(
file_temp,
file_temp.translate(str.maketrans('', '', '0123456789'))
)
Incidentally, that's also how the Python 2 unicode.translate()
works.
Upvotes: 4