2016-05-14 151 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