是否有从文件名中提取扩展名的功能?
当前回答
使用os.path.splitext:
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
与大多数手动字符串拆分尝试不同,os.path.splitext将正确地将/a/b.c/d视为没有扩展名而不是扩展名.c/d,并将.bashrc视为没有延伸名而不是具有扩展名.bashrc:
>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')
其他回答
使用splitext时,具有双扩展名的文件存在问题(例如file.tar.gz、file.tar.bz2等)
>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension
'.gz'
但应该是:.tar.gz
可能的解决方案如下
如果你喜欢正则表达式,那就是一个真正的单行。即使中间有额外的“.”也无关紧要
import re
file_ext = re.search(r"\.([^.]+)$", filename).group(1)
查看此处查看结果:单击此处
我知道我迟到了
这是我的简单解决方案
file = '/foo/bar/whatever.ext'
extension = file.split('.')[-1]
print(extension)
#output will be ext
filename='ext.tar.gz'
extension = filename[filename.rfind('.'):]
如果您想提取最后一个文件扩展名,如果它有多个
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,即使只有一个扩展名也能正常工作
推荐文章
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数
- 滚动或滑动窗口迭代器?
- python的方法找到最大值和它的索引在一个列表?
- 如何读取文件的前N行?
- 如何删除matplotlib中的顶部和右侧轴?
- 解析.py文件,读取AST,修改它,然后写回修改后的源代码
- Visual Studio Code:如何调试Python脚本的参数
- 使用元组/列表等等。从输入vs直接引用类型如list/tuple/etc
- 结合conda环境。Yml和PIP requirements.txt
- 将命名元组转换为字典
- 如何使x轴和y轴的刻度相等呢?
- Numpy在这里函数多个条件