2016-05-14 152 views
0

在用户输入上,我试图验证他们输入了合适的文件扩展名。例如:检查有效的文件扩展名

file1 = input('Enter the file name ending in ".txt": ') 

我想验证他们是否输入了'.txt'。现在我正在做非常基本的检查。但是,下面的检查并没有真正验证文件是否以.txt结尾。

if '.txt' not in file_name: 
    print('Include file extension (example): ".txt"') 

所以我认为它只验证'txt'字符存在''后。但只有当这是最终的'。'时,例如,我不希望它意外地捕捉到baby.dinosoars.txt中的“dinosoars”。

+1

[Checkingtofileextensions](http://stackoverflow.com/questions/5899497/checking-file-extension) –

回答

2

如果你把你的文件名转换成字符串s,你可以使用的endsWith:

if s.endswith('.txt'): 
... 
elif s.endswith('.test'): 
... 

或者不区分大小写的版本(和消除任何其他人,如果链)

s.lower().endswith(('.png', '.jpg', '.jpeg')) 
1

为什么不用endswith代替?

if not file_name.endswith(extension): 
    #exec code 
1

这应该工作:

if file_name.endswith(".txt"): 
    print "something" 
+0

'endswith'而不是'ends_with'和'print'在Python 3.x中需要括号 – Pythonista