-5

Here is my code :

import os
def rename_file ():
    file_list = os.listdir (r"C:\Users\Sushant\Desktop\test")
    print (file_list)

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

rename_file ()

result :

os.rename(file_name, file_name.translate(None , "0123456789" ))
TypeError: translate() takes exactly one argument (2 given)

Why do I keep getting this error ? I have just kept a file with some numbers and want to remove it .

Md. Rezwanul Haque
  • 2,882
  • 7
  • 28
  • 45
JOh
  • 11
  • 1
  • Remove None from the translate arguments – Mohamed Ali JAMAOUI Jul 27 '17 at 07:32
  • 1
    You should read compiler errors more carefully, it is all written there: it complains that translate function takes exactly one argument, but you are trying to pass two `translate(None , "0123456789" )` – Viktor Chvátal Jul 27 '17 at 07:33
  • Actually, `string.translate` can take two arguments, as stated here https://docs.python.org/2/library/string.html#string.translate. So, Viktor, your comment doesn't help. – Fejs Jul 27 '17 at 07:53

3 Answers3

1

You are using the translate method wrong. The translate method needs a dict created by the maketrans method.

output = ("abcdefabc").translate(str.maketrans("abc", "123"))

Thre print will read out: 123def123

Magnus Wang
  • 170
  • 1
  • 2
  • 6
1

I guess You're using Python3, since this is valid syntax in Python2. For Python3, use following:

import os
def rename_file():
    file_list = os.listdir(r"C:\Users\Sushant\Desktop\test")
    print(file_list)

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

rename_file()

And here's the docs for maketrans function.

Fejs
  • 2,734
  • 3
  • 21
  • 40
0

When using translate() you have to pass in a table made by maketrans() as the first argument. This is the reason for getting a TypeError since you are passing in None.

With maketrans() you pass in the character you want to change in one string. The second argument is a string with the character you want to put in their place. This function returns a table, which you then pass into translate().

In your case something like this would work.

file_name.translate(str.maketrans("", "", "0123456789"))

Further reading on maketrans() and translate()

PeskyPotato
  • 670
  • 8
  • 20