-4
import os

def rename_files():
    file_list = os.listdir(r"D:\360Downloads\test")
    saved_path = os.getcwd()
    os.chdir(r"D:\360Downloads\test")

    for file_name in file_list:
        os.rename(file_name, file_name.translate(None,"0123456789"))

rename_files()

the error message is TypeError: translate() takes exactly one argument (2 given). How can I format this so that translate() does not return an error?

A Magoon
  • 1,180
  • 2
  • 13
  • 21
Jack
  • 56
  • 5

1 Answers1

1

Hope this helps!

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

or

os.rename(file_name,file_name.translate({ ord(i) : None for i in '0123456789' }))

Explanation:

I think you're using Python 3.x and syntax for Python 2.x. In Python 3.x translate() syntax is

str.translate(table)

which takes only one argument, not like Python 2.x in which translate() syntax is

str.translate(table[, deletechars])

which can takes more than one arguments.

We can make translation table easily using maketrans function. In this case, In first two parameters, we're replacing nothing to nothing and in third parameter we're specifying which characters to be removed.

We can also make translation table manually using dictionary in which key contains ASCII of before and value contains ASCII of after character.If we want to remove some character it value must be None. I.e. if we want to replace 'A' with 'a' and remove '1' in string then our dictionary looks like this

{65: 97, 49: None}

Mohsin
  • 11
  • 2