Search code examples
pythonnomenclature

Test whether a file name has the correct naming convention in Python


How can I test whether a file name has the correct naming convention in Python? Say I want file names to end with the string _v and then some number and then .txt. How would I do that? I have some example code which expresses my idea, but doesn't actually work:

fileName = 'name_v011.txt'
def naming_convention(fileName):
    convention="_v%d.txt"
    if fileName.endswith(convention) == True:
        print "good"
    return
naming_convention(fileName)

Solution

  • You could use a regular expression using Python's re module:

    import re
    
    if re.match(r'^.*_v\d+\.txt$', filename):
        pass  # valid
    else:
        pass  # invalid
    

    Let's pick the regular expression apart:

    • ^ matches the start of the string
    • .* matches anything
    • _v matches _v literally
    • \d+ matches one or more digits
    • \.txt matches .txt literally
    • $ matches the end of the string