[英]How do I look up for a specific part / extension of file name?
I want to look for the extension of a filename, and the extension can only be 3 characters long. 我想查找文件名的扩展名,并且扩展名只能是3个字符长。
it is something like, 就像
filename = str(input("Please enter filename: "))
then I want to execute a task to look for the extension, and if the extension doesn't fulfill the requirement (ie 3 characters long), I'll add print "Invalid extension!" 然后我要执行任务以查找扩展名,如果扩展名不符合要求(即3个字符长),我将添加打印“无效扩展名!”。 Else, print "Valid extension."
否则,打印“有效扩展名”。
len(os.path.splitext('/foo/file.png')[1]) - 1 == 3
You can "cut" it like that if the extension is always 3 caracters : 如果扩展名始终是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
See Extracting extension from filename in Python too 另请参阅在Python中从文件名提取扩展名
Edit : You can rely on the mime type instead, depending of your needs, see How to find the mime type of a file in python? 编辑 :您可以依赖于mime类型,具体取决于您的需求,请参阅如何在python中查找文件的mime类型?
This should do what you are describing: 这应该按照您的描述进行:
filename = raw_input("Please enter filename: ") #This is already a string
if len(filename.split('.')[-1])==3:
print "Valid extension"
else:
print "Invalid extension!"
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.