简体   繁体   English

如何查找文件名的特定部分/扩展名?

[英]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.

相关问题 如何在文件名中查找文本片段? - How do I look for a text fragment within a file name? 当文件名是 python 中的变量时,如何更改文件名的一部分? - How do I change part of a file name when it is a variable in python? 如何在文件中查找特定文本,然后在 Python 中找到它时返回其受尊重的文件名? - How do I look for a particular text in file and then return it's respected file name when found in Python? 如何删除文件基名的一部分并将其附加到文件名的末尾? - How do I remove part of a file base name and attach it to the end of the file name? 如何删除字符串的特定部分? - How do I remove a specific part of a string? Select 文件名中的特定部分 - Select specific part in file name 如何在VSCode中查找当前上下文? - How do I look up the current context in VSCode? 如何获取文件名中包含特定年份的文件? - How do I grab files with specific years in the file name? 如果我知道目标网页和文件扩展名但不知道文件名,我该如何使用爬虫? - How do I use crawler if I know the target web-page and file extension but not knowing the file name? 在Python中,如何将基于扩展名的文件名从文本文件中拉出并放入新的文本文件中? - In Python, how do I pull the file name based on extension out of a text file and place in new text file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM