Alex February 2016

How to remove all numbers from a file name or a string - Python3

I have a Python script that will walk through all of the directories within the Test Folder(in this case) and will remove all numbers at the beginning of each of the file names. So my question is how would I modify my script in order to remove numbers from the whole file name? Not just the beginning or the end of it.

Thanks, Alex

import os

for root, dirs, files in os.walk("Test Folder", topdown=True):
    for name in files:
        if (name.startswith("01") or name.startswith("02") or name.startswith("03") or name.startswith("04") or name.startswith("04") or name.startswith("05") or name.startswith("06") or name.startswith("07") or name.startswith("08") or name.startswith("09") or name[0].isdigit()):
            old_filepath = (os.path.join(root, name))
            _, new_filename = name.split(" ", maxsplit=1)
            new_filepath = (os.path.join(root, new_filename))
            os.rename(old_filepath, new_filepath)


tobias_k February 2016

Use regular expression, particularly re.sub:

>>> import re
>>> filename = '12name34with56numbers78in9it.txt'
>>> re.sub(r'\d', '', filename)

This replaces everything that matches the \d pattern, i.e. that is a number, with '', i.e. nothing.

If you want to protect the extension, it get's more messy. You have to split the extension from the string, replace numbers in the first part, then join the extension back on. os.path.splitext can help you with that:

>>> filename = '12name34with56numbers78in9it.mp3'
>>> name, ext = os.path.splitext(filename)
>>> re.sub(r'\d+', '', name) + ext

zondo February 2016

You can do this:

filename = "this2has8numbers323in5it"
filename = "".join(char for char in filename if not char.isdigit())

No imports necessary.

Post Status

Asked in February 2016
Viewed 2,371 times
Voted 4
Answered 2 times


Leave an answer