Reputation: 117
On user input I am trying to validate they typed an appropriate file extension. For example:
file1 = input('Enter the file name ending in ".txt": ')
I'd like to validate that they entered '.txt'. Right now I'm doing very basic checking. However, the check below doesn't really validate that the file 'ends' in .txt.
if '.txt' not in file_name:
print('Include file extension (example): ".txt"')
So I suppose its validating only 'txt' characters exist after '.' but only if that is the final '.', for example, I wouldn't want it to accidentally catch on "dinosoars" in baby.dinosoars.txt.
Upvotes: 0
Views: 2355
Reputation: 462
If you make your filename into a string s
, you can use endswith:
if s.endswith('.txt'):
...
elif s.endswith('.test'):
...
Or the case-insensitive version (and eliminate any else-if chain)
s.lower().endswith(('.png', '.jpg', '.jpeg'))
Upvotes: 4
Reputation: 11645
Why not use endswith
instead?
if not file_name.endswith(extension):
#exec code
Upvotes: 1