Rich Johnson Rich Johnson - 11 months ago 105
Python Question

Python - Filename validation help needed

Bad Filename Example:

foo is-not_bar-3.mp4

What it should be:

I only want to keep a
for the last bit of the string if it is a digit followed by the extension. The closest I have gotten thus far is with the following code:

fname = 'foo is-not_bar-3.mp4'
valchars = '-_. %s%s' % (string.ascii_letters, string.digits)
f = ''.join(c for c in fname if c in valchars).replace(' ', '_').replace('-', '_')

Answer Source

You can use regex replacement with a negative lookahead:

import re

fname = 'foo is-not_bar-3.mp4'
f = re.sub(r'\s|-(?!\d+)', '_', fname)
>> 'foo_is_not_bar-3.mp4'

This will replace every - and space with _ unless it is followed by a number.