Python 3x – Remove numbers from file names

Question:

import os

def rename_files():
    # (1) get file names from a folder
    file_list = os.listdir(r"C:UsersUSEERDesktopUdacityUdacity - Programming Foundation with PythonProjectprankprank")

    # print(file_list)
    saved_path = os.getcwd()
    print("Current Working Directory is " + saved_path)
    os.chdir(r"C:UsersUSEERDesktopUdacityUdacity - Programming Foundation with PythonProjectprankprank")

    # (2) for each file, rename file name
    for file_name in file_list:
        print("Old Name - " + file_name)
        print("New Name - " + file_name.translate("0123456789"))
        os.rename(file_name, file_name.translate("0123456789"))
    os.chdir(saved_path)

rename_files()

The code above doesn’t rename the file by removing the integers. Can anyone help? (Python 3x)

Asked By: Jean Bernard FLORE

||

Answers:

import re

new_name = re.sub('[0-9]', '', file_name)
Answered By: jfsturtz

The problem is in your translate function that doesn’t do anything. There are better options available, but if your want to use translate then the proper syntax is:

#!/usr/bin/env python2

import string
new_name = string.translate(file_name, None, "0123456789")
Answered By: Harald Nordgren

Another way to do this without import re. Instead of utilizing the .translate, use the .strip.

os.rename(file_name, file_name.strip('0123456789'))

Another observation is that your code wont read the new file name after changing it. At the top of your code you are reading file names and saving those name in file_list

# (1) get file names from a folder
file_list = os.listdir(r"C:UsersUSEERDesktopUdacityUdacity - Programming Foundation with PythonProjectprankprank")

In the for loop, where you are changing the name of each file, YOU ARE NOT reading the new file’s name. You need to do something like this.

# (2) for each file, rename file name
for file_name in file_list:
    print("Old Name - " + file_name)
    os.rename(file_name, file_name.strip("0123456789"))

# (3) read file's name again... 'file_list' has old names
new_file_list = os.listdir(r"C:UsersUSEERDesktopUdacityUdacity - Programming Foundation with PythonProjectprankprank")
for file_name in new_file_list:
    print("New file's name: " + new_file_name)

os.chdir(saved_path)
Answered By: redeemefy

In Python 3 the String.translate is gone. Therefore you need to use the str.translate. It needs ‘str.maketrans’ which normally creates a translation table with the first two arguments supplied(not needed in this example), the third argument supplies the characters to be stripped.

This line should have the desired effect …

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

Previous suggestions used .strip() however in this case as the numbers are mixed in with the filenames (not before or after) I believe it would not work, another used Regular Expressions which is perfectly valid, however within the context of this particular Udacity course translate was the suggested solution.

Here are the docs for maketrans :
[https://docs.python.org/3/library/stdtypes.html#str.maketrans][1]

Answered By: Inyoka

Here is one way of renaming files.

  1. Use os.renames to rename the files
  2. Use file_name.strip("0123456789") to remove numbers

Code is given below:

import os
def file_rename():
    name_list=os.listdir(r"C:pythonprank")
    print(name_list)
    saved_path=os.getcwd()
    print("Current working directory is"+saved_path)
    os.chdir(r"C:pythonprank")

    for file_name in name_list:
        print("old name"+file_name)
        print("new name"+file_name.strip("0123456789"))
        os.renames(file_name,file_name.strip("0123456789"))
    os.chdir(saved_path)

file_rename()

To read more about os.renames check here.
To read more about the strip function, check here.

Answered By: Anu Moudgil
import os

def rename_files():
    #1 Get file names from the folder
    file = os.listdir(r"C:WebPythonprank")
    print(file)
    saved_path = os.getcwd()
    print("Current Working Directory is"+saved_path)
    os.chdir(r"C:WebPythonprank")

    #2 For each file name rename file names
    for file_name in file:
       print("Old Name - " + file_name)
       os.rename(file_name,file_name.strip("0123456789"))
       print("New Name - " + file_name)

    os.chdir(saved_path)
rename_files()
Answered By: ujjawal indwar

will guys i was trying to solve this problem because i see udacity online courses and it require to rename file without numbers thanks to simon for his replay i have to figured it out

this is my code to rename files without numbers, hope it jhelp anyone who stuck

import os
import re

def rename():

    #get the list of the photo name
    plist = os.listdir(r"D:payprank")
    print(plist)
    #removing the numbers from the photo names

    os.chdir(r"D:payprank")
    for pname in plist :
        os.rename(pname, re.sub('[0-9]', '' , pname))
        print(pname)
rename()
Answered By: dejo sensi
enter code here
import os

dir="/home/lucidvis/myPythonHome/prank/"

def rename_files():

# get file names from a folder
    filenames = os.listdir(dir)
   # print(filenames)
    for file in filenames:
        #print(file)
        try:
            #with os.open(filename for filename in filenames,"r+"):
               #read_file = filename.read()

       # new_name = file.translate(str.maketrans('','', "0123456789"))
            new_filname = (file.translate(str.maketrans('','', "0123456789"))).replace(" ","")
            #print(dir+new_file_name)
            os.rename(dir+file,dir+new_file_name)
        except SyntaxError as e:
            print(e)
            continue

# for each file, rename filename
rename_files()

import os

dir="/home/lucidvis/myPythonHome/prank/"

def rename_files():

# get file names from a folder
    filenames = os.listdir(dir)
# iterate through the list of filenames
    for file in filenames:
        #print(file)
        try:              
#assign a variable to new names for easy manipulation
            new_filname = (file.translate(str.maketrans('','', "0123456789"))).replace(" ","")
            #concatenating the directory name to old and new file names 
            os.rename(dir+file,dir+new_file_name)
#just to manage errors
        except SyntaxError as e:
            print(e)
            continue

#file renaming function call
rename_files()

Answered By: qova
  import os
  import re
  from string import digits

  #Get file names

  file_list = os.listdir(r"C:Users703305981Downloadsprankprank")
  print(file_list)

  #chenage directory.

  os.chdir(r"C:Users703305981Downloadsprankprank")
  print (os.getcwd())

  #Change the Name.

   for file_name in file_list:
       os.rename(file_name, re.sub(r'[0-9]+', '', file_name))
Answered By: Coder_bibi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.