Jean Bernard FLORE Jean Bernard FLORE - 4 months ago 35
Python Question

Python 3x - Remove numbers from file names

import os

def rename_files():
# (1) get file names from a folder
file_list = os.listdir(r"C:\Users\USEER\Desktop\Udacity\Udacity - Programming Foundation with Python\Project\prank\prank")

# print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\USEER\Desktop\Udacity\Udacity - Programming Foundation with Python\Project\prank\prank")

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

Answer
import re

new_name = re.sub('[0-9]', '', file_name)
Comments