tjshah050291
tjshah050291

Reputation: 71

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

  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)

Upvotes: 4

Views: 2672

Answers (4)

Jay Narayan
Jay Narayan

Reputation: 19

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

Upvotes: 0

Chandan Patil
Chandan Patil

Reputation: 31

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()

Upvotes: 3

user7599893
user7599893

Reputation:

Replace

file_name.translate(None, "01234567789")

With

 file_name.strip("01234567789")

Upvotes: 1

user554546
user554546

Reputation:

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()

Upvotes: 3

Related Questions