Reputation: 459
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)
Upvotes: 2
Views: 1684
Reputation: 128991
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 stringUpvotes: 4