Translate () takes exactly one argument (2)

I want to write a python program to rename all files from a folder to remove numbers from the filename, for example: chicago65.jpg will be renamed to chicago.jpg.

Below is my code, but I am getting an error as translate () only takes 1 argument. help resolve 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()

      

+3


source to share


2 answers


You are using Python 2 signature str.translate()

in Python 3. There method only takes 1 argument , mapping from code points (integers) to replacement or None

to remove that code.

Instead, you can create a mapping with a str.maketrans()

static method
:



os.rename(
    file_temp, 
    file_temp.translate(str.maketrans('', '', '0123456789'))
)

      

By the way, this is also how Python 2 works unicode.translate()

.

+3


source


If all you want to do is do the same thing that you did in Python 2 in Python 3, here's what I did in Python 2.0 to get rid of the punctuation marks and numbers:

text = text.translate(None, string.punctuation)
text = text.translate(None, '1234567890')

      

Here's my Python 3.0 equivalent:



text = text.translate(str.maketrans('','',string.punctuation))
text = text.translate(str.maketrans('','','1234567890'))

      

Basically, it says "translate nothing" (the first two parameters) and translate any punctuation marks or numbers to "None" (ie remove them).

0


source







All Articles