Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

translate() takes exactly one argument (2 given)

Tags:

python

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()
like image 231
ArkalaMounikasai Avatar asked Oct 16 '25 15:10

ArkalaMounikasai


2 Answers

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.

like image 146
Martijn Pieters Avatar answered Oct 19 '25 13:10

Martijn Pieters


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).

like image 20
Yashi Aggarwal Avatar answered Oct 19 '25 13:10

Yashi Aggarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!