Issue with renaming a bunch of files in a directory using Python

2.6k Views Asked by At
  import os
    def rename_files():
        file_list = os.listdir(r"G:\Python_Learning\prank")
        print(file_list)
        saved_path =os.getcwd()
        print("Current working directory is "+saved_path)
        os.chdir(r"G:\Python_Learning\prank")
        for file_name in file_list:
            os.rename(file_name,file_name.translate(None, "0123456789"))
            os.chdir(saved_path)
    rename_files()

Here is the stack trace:

     1. -Error: -Traceback (most recent call last): -File 
"C:/Python34/rename_files.py", line 11, in <module> -rename_files()
        -File "C:/Python34/rename_files.py", line 9, in rename_files -os.rename(file_name,file_name.translate(None, b"0123456789")) -TypeError: translate() takes exactly one argument (2 given)
4

There are 4 best solutions below

11
AudioBubble On BEST ANSWER

In Python 3, str.translate takes only one argument:

str.translate(map) Return a copy of the s where all characters have been mapped through the map which must be a dictionary of Unicode ordinals (integers) to Unicode ordinals, strings or None. Unmapped characters are left untouched. Characters mapped to None are deleted.

You can use str.maketrans() to create a translation map from character-to-character mappings in different formats.

Note An even more flexible approach is to create a custom character mapping codec using the codecs module (see encodings.cp1251 for an example).

This works differently from str.translate in Python 2.

If you're just trying to remove characters, you can use re.sub:

import os
import re

def rename_files():
    file_list = os.listdir(r"G:\Python_Learning\prank")
    print(file_list)
    saved_path =os.getcwd()
    print("Current working directory is "+saved_path)
    os.chdir(r"G:\Python_Learning\prank")
    for file_name in file_list:
        os.rename(file_name,re.sub("[0-9]","", file_name))
        os.chdir(saved_path)
rename_files()
0
Chandan Patil On

Use str.strip().

import os
def rename_files():
    file_list = os.listdir(r"G:\Python_Learning\prank")
    print(file_list)
    saved_path =os.getcwd()
    print("Current working directory is "+saved_path)
    os.chdir(r"G:\Python_Learning\prank")
    for file_name in file_list:
        os.rename(file_name,file_name.strip("0123456789"))
        os.chdir(saved_path)
rename_files()
0
AudioBubble On

Replace

file_name.translate(None, "01234567789")

With

 file_name.strip("01234567789")
1
Jay Narayan On

os.rename(file_name, file_name.strip("01234567789"))