我想查找文件名的扩展名,扩展名只能是3个字符。
就像是,
filename = str(input("Please enter filename: "))
然后我想执行一个任务来查找扩展名,如果扩展名不满足要求(即3个字符长),我将添加print“Invalid extension!”否则,请打印“有效的扩展名。”
答案 0 :(得分:7)
len(os.path.splitext('/foo/file.png')[1]) - 1 == 3
答案 1 :(得分:0)
如果扩展名总是3个字符,你可以“剪切”它:
$ python2
Python 2.7.2 (default, Jan 31 2012, 13:19:49)
[GCC 4.6.2 20120120 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x = "file.ext"
>>> print x[-3:]
ext
另见Extracting extension from filename in Python
修改:您可以依赖mime类型,具体取决于您的需求,请参阅How to find the mime type of a file in python?
答案 2 :(得分:0)
这应该按照你的描述进行:
filename = raw_input("Please enter filename: ") #This is already a string
if len(filename.split('.')[-1])==3:
print "Valid extension"
else:
print "Invalid extension!"
希望这有帮助。