-6

This is an assignment that needs to change the name of the file within a certain folder, however, it doesn't change the name after all. Can anyone help?

import os

def rename_files():
    file_list = os.listdir(r"C:\Users\Downloads\prank")
    saved_path = os.getcwd()
    print("Current Working Directory is " +saved_path)
    os.chdir(r"C:\Users\Downloads\prank")
    for file_name in file_list:
        os.rename(file_name, file_name.translate(None, "0123456789"))
    os.chdir(saved_path)

rename_files()

result:

Traceback (most recent call last):
  File "C:\Users\Downloads\prank\rename_files.py", line 10, in <module>
    rename_files()
  File "C:\Users\Downloads\prank\rename_files.py", line 8, in rename_files
    os.rename(file_name, file_name.translate(None, '0123456789'))
TypeError: translate() takes exactly one argument (2 given)

This code works in Python 2, but does not work in Python 3. How can it be made to work in Python 3.6, I only need to delete characters.

Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997
Roxanne
  • 1
  • 1

1 Answers1

2

You are confusing the Python 2 str.translate() method with the Python 3 version (which is really the same as unicode.tranlate() in Python 2).

You can use the str.maketrans() static method to create a translation map; pass your string of digits to be removed in as the third argument to that function:

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

Better still, store the result of str.maketrans() outside of the loop, and re-use it:

no_digits = str.maketrans('', '', '0123456789')

for file_name in file_list:
    os.rename(file_name, file_name.translate(no_digits))
Martijn Pieters
  • 889,049
  • 245
  • 3,507
  • 2,997