是否有从文件名中提取扩展名的功能?
当前回答
对于简单的用例,一个选项可能是从点拆分:
>>> filename = "example.jpeg"
>>> filename.split(".")[-1]
'jpeg'
文件没有扩展名时没有错误:
>>> "filename".split(".")[-1]
'filename'
但你必须小心:
>>> "png".split(".")[-1]
'png' # But file doesn't have an extension
也不会在Unix系统中处理隐藏文件:
>>> ".bashrc".split(".")[-1]
'bashrc' # But this is not an extension
对于一般用途,首选os.path.splitext
其他回答
a = ".bashrc"
b = "text.txt"
extension_a = a.split(".")
extension_b = b.split(".")
print(extension_a[-1]) # bashrc
print(extension_b[-1]) # txt
我知道我迟到了
这是我的简单解决方案
file = '/foo/bar/whatever.ext'
extension = file.split('.')[-1]
print(extension)
#output will be ext
如果您想提取最后一个文件扩展名,如果它有多个
class functions:
def listdir(self, filepath):
return os.listdir(filepath)
func = functions()
os.chdir("C:\\Users\Asus-pc\Downloads") #absolute path, change this to your directory
current_dir = os.getcwd()
for i in range(len(func.listdir(current_dir))): #i is set to numbers of files and directories on path directory
if os.path.isfile((func.listdir(current_dir))[i]): #check if it is a file
fileName = func.listdir(current_dir)[i] #put the current filename into a variable
rev_fileName = fileName[::-1] #reverse the filename
currentFileExtension = rev_fileName[:rev_fileName.index('.')][::-1] #extract from beginning until before .
print(currentFileExtension) #output can be mp3,pdf,ini,exe, depends on the file on your absolute directory
输出为mp3,即使只有一个扩展名也能正常工作
如果你喜欢正则表达式,那就是一个真正的单行。即使中间有额外的“.”也无关紧要
import re
file_ext = re.search(r"\.([^.]+)$", filename).group(1)
查看此处查看结果:单击此处
您可以使用以下代码拆分文件名和扩展名。
import os.path
filenamewithext = os.path.basename(filepath)
filename, ext = os.path.splitext(filenamewithext)
#print file name
print(filename)
#print file extension
print(ext)
推荐文章
- 如何在交互式Python中查看整个命令历史?
- 如何显示有两个小数点后的浮点数?
- 如何用OpenCV2.0和Python2.6调整图像大小
- 在每个列表元素上调用int()函数?
- 当使用代码存储库时,如何引用资源的相对路径
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?